简体   繁体   中英

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

So I tried my own solution in C++ but there is a bug in the code. That problem comes from judge. So what I'm doing is keep adding a sum value and then check if the provided sum equals to the total sum in a leaf.

bool hasPathSum(TreeNode *root, int sum) {

    stack<TreeNode*> st; 

    TreeNode *temp = root;
    int SUM = 0;    
    bool hasSum = false;
    st.push(temp);
    while(!st.empty() && temp != NULL)
    {
        if(temp)
        {
            st.push(temp);
            temp = temp->left;
        }
        else
        {      
            st.pop();
            temp = st.top();
            SUM += temp->val;
            if(SUM == sum)
                hasSum = true;
            temp = temp->right;
        }
    }
   return hasSum; 
}

Trivial to express recursively:

bool hasPathSum(TreeNode *node, int sum) {
    if (!node) {
        return sum == 0;
    }
    return hasPathSum(node->left, sum-node->val) ||
           hasPathSum(node->right, sum-node->val);
}

If you translate this to a stack implementation, you will see some of the problems in yours. In particular, it is only at the leaves you want to check the sum (you check interior nodes). You have to adjust the sum as you go up and down the tree (you always add to it).

public static boolean hasPathSum(TreeNode node, int targetSum) {  
        if (node == null) return false;
        targetSum-= node.val;
        if (targetSum == 0 && node.left==null && node.right==null) {
            return true;
        }
        int left = hasPathSum(node.left, targetSum);
        int right = hasPathSum(node.right, targetSum;
        return left || right;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM