繁体   English   中英

给定一棵二叉树和一个总和,确定这棵树是否有根到叶的路径,使得沿路径的所有值相加等于给定的总和

[英]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

所以我在 C++ 中尝试了我自己的解决方案,但代码中有一个错误。 那个问题来自法官。 所以我正在做的是继续添加一个总和值,然后检查提供的总和是否等于叶子中的总和。

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; 
}

递归地表达很简单:

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

如果您将其转换为堆栈实现,您将看到您的一些问题。 特别是,它仅在您想要检查总和的叶子上(您检查内部节点)。 当你在树上上下移动时,你必须调整总和(你总是添加它)。

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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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