Thursday, January 30, 2014

[leetcode] 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.
My Code:
 bool hasPathSum(TreeNode *root, int sum) {
        if(!root) return false;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* cur = q.front();
            if(!cur->left && !cur->right){
                if(cur->val == sum)
                    return true;
            }
            else{
                if(cur->left){
                    cur->left->val = cur->val + cur->left->val;
                    q.push(cur->left);
                }
                if(cur->right){
                    cur->right->val = cur->val + cur->right->val;
                    q.push(cur->right);
                }
            }
            q.pop();
        }
        return false;
    }

No comments:

Post a Comment