Saturday, August 31, 2013

Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:


[
  [3],
  [9,20],
  [15,7]
]
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function

    vector<vector<int> > result;
    vector<int> v;
    
    if(!root)
        return result;
    
    queue<TreeNode *> Q;
    Q.push(root);
    Q.push(NULL);
    while(Q.size() > 1)
    {
        TreeNode *top = Q.front();
        Q.pop();
        
        if(top == NULL)
        {
            result.push_back(v);
            v.clear(); 
            Q.push(NULL);
        }
        else
        {
            v.push_back(top->val);
       if(top->left)
            Q.push(top->left);
        
        if(top->right)
            Q.push(top->right);            
        }
        
 
    }
    
    result.push_back(v);    
    Q.pop();
    return result;
}
};

Path Sum - II (Print all Paths sum to target)

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return


[
   [5,4,11,2],
   [5,8,4,5]
]


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
void check(TreeNode *root, vector<int> v, vector<vector<int> > &result, int current_sum, int target_sum)
{
    if(!root)
        return;
    
    current_sum += root->val;
    v.push_back(root->val);
    if(!root->left && !root->right)
    {
        if(current_sum == target_sum)
        result.push_back(v);
        return ;
    }
    
    
    check(root->left, v, result,  current_sum, target_sum) ;
    check(root->right, v, result, current_sum, target_sum);
                
 }

vector<vector<int> > pathSum(TreeNode *root, int sum) {
    vector<int> v;
    vector<vector<int> > vr;
    check(root, v, vr, 0, sum);
    return vr;
}
};

Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
bool check(TreeNode *root, int current_sum, int target_sum)
{
    if(!root)
        return false;
    current_sum += root->val;
    
    if(!root->left && !root->right)
    {
        return (current_sum  == target_sum);
    }
    
    
    return check(root->left, current_sum, target_sum) || check(root->right, current_sum, target_sum);
                
 }

bool hasPathSum(TreeNode *root, int sum) 
{
    if(!root)
        return false;
    return check(root, 0, sum);
}

};

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
 /**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
      if(!root)  return 0;
      return 1 + max(maxDepth(root->left), maxDepth(root->right));
   }
};

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
       /**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
          if(!root)
             return 0;
          int left  = minDepth(root->left);
          int right  = minDepth(root->right);
          if((left  == 0 && right > 0) || (right  == 0 && left > 0))
            return 1  + max(left, right);
         return 1 + min(left, right);
    }
};


Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
       1
      / \
     2   3
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
int setmax(TreeNode *root, int &maxv)
{
    if(!root) return 0;
        
    int leftmax  = setmax(root->left, maxv);
    int righmax  = setmax(root->right, maxv);
    
    int maxp = root->val;
    if(leftmax > 0) maxp += leftmax;
    if(righmax > 0)  maxp += righmax;
    
    maxv = max(maxv, maxp);
    return max(root->val, root->val+  max(leftmax, righmax));
}

int maxPathSum(TreeNode *root) {
     if(!root)
                return 0;
    int maxc  =  root->val;
    setmax(root, maxc);
    return maxc;
}

};