【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
return true, as there exist a root-to-leaf path
递归的解法:
只考虑当前结点的成败条件,对于儿子,则交给递归去做。
读到某个结点,计算路径val之和,之后判断,如果不是叶子结点,递归调用函数进入其子孙结点。如果是叶子结点,当val之和与sum值相等,返回true,不相等返回false。
注意:
1、注意题目是“root-to-leaf”即计算根节点到叶子节点的加和,不要只计算到某个枝干,即使运算到某个枝干时,sum值已经相等,也不能返回true;
2、注意可能出现正数负数混杂的情况;
迭代的解法:
附录:
用迭代法遍历二叉树思路总结
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->2which 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; } };
附录:
用迭代法遍历二叉树思路总结
相关文章推荐
- 【leetcode】path sum--easy
- LeetCode112. Path Sum(Easy)
- Leetcode 112. Path Sum (Easy) (cpp)
- 【LeetCode】112.Path Sum(Easy)解题报告
- leetcode_题解_path sum_easy
- LeetCode刷题(C++)——Path Sum(Easy)
- Leetcode[Easy] - Path Sum
- 【Leetcode】【Easy】Merge Two Sorted Lists
- leetcode 520. Detect Capital(easy)
- 【LeetCode】(C#)155. Min Stack(Easy)
- leetcode 506. Relative Ranks(easy)
- [LeetCode]Path Sum
- leetcode_242_Valid Anagram(easy)(C++)(Java)
- LeetCode-566:Reshape the Matrix (矩阵整型)-- easy
- Leetcode 541. Reverse String II(Easy)
- 【LeetCode】(94)Binary Tree Inorder Traversal(Easy)
- 【leetcode】【Easy】【463. Island Perimeter】
- LeetCode: 继续easy题3
- Leetcode 557. Reverse Words in a String III (Easy)
- 【Leetcode】【Easy】Balanced Binary Tree