您的位置:首页 > 其它

【Leetcode】【Easy】Path Sum

2014-11-21 23:39 323 查看
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.

递归的解法:

只考虑当前结点的成败条件,对于儿子,则交给递归去做。

读到某个结点,计算路径val之和,之后判断,如果不是叶子结点,递归调用函数进入其子孙结点。如果是叶子结点,当val之和与sum值相等,返回true,不相等返回false。

注意:

1、注意题目是“root-to-leaf”即计算根节点到叶子节点的加和,不要只计算到某个枝干,即使运算到某个枝干时,sum值已经相等,也不能返回true;

2、注意可能出现正数负数混杂的情况;

/**
* 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 hasPathSum(TreeNode *root, int sum) {
if (!root)
return false;

int curSum = sum - root->val;

if (!root->left && !root->right && curSum == 0)
return true;

return hasPathSum(root->left, curSum) || \
hasPathSum(root->right, curSum);

}
};


迭代的解法:

class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
stack<TreeNode *> nodeStack;
TreeNode *preNode = NULL;
TreeNode *curNode = root;
int curSum = 0;

while (curNode || !nodeStack.empty()) {
while (curNode) {
nodeStack.push(curNode);
curSum += curNode->val;
curNode = curNode->left;
}

curNode = nodeStack.top();

if (curNode->left == NULL && \
     curNode->right == NULL && \
     curSum == sum) {
return true;
}

if (curNode->right && preNode != curNode->right) {
curNode = curNode->right;
} else {
preNode = curNode;
nodeStack.pop();
curSum -= curNode->val;
curNode = NULL;
}
}
return false;
}
};


附录:

用迭代法遍历二叉树思路总结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: