pranay_teja
11/21/2018 - 7:02 AM

PathSum

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    // Iterative solution
    
    bool hasPathSum(TreeNode* root, int sum){
        if(root==NULL){
            return false;
        }
        stack<TreeNode*> st;
        stack<int> sums; // sums for different branches
        st.push(root);
        sums.push(sum);
        while( !st.empty() && !sums.empty()){
            int currSum=sums.top();
            TreeNode* curr=st.top();
            st.pop();
            sums.pop();
            if(curr->right==NULL && curr->left==NULL && curr->val==currSum){
                return true;
            }
            if(curr->right){
                st.push(curr->right);
                sums.push(currSum-(curr->val));
            }
            if(curr->left){
                st.push(curr->left);
                sums.push(currSum-(curr->val));
            }
        }
        return false;
    }
    
    // Recursive solution
//     bool hasPathSum(TreeNode* root, int sum) {
//         if(root==NULL){
//             return false; // if no tree, not possible
//         }
//         if(root->right==NULL && root->left==NULL){ // if leaf node
//             if(sum==root->val){ // if node val == sum reqd
//                 return true;
//             }
//             return false;
//         }
//         sum-=root->val; // substract curr root val
        
//         // check if any left OR right has the reqd path
//         return( hasPathSum(root->left,sum) || hasPathSum(root->right,sum) );
//     }
};