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.
[Thoughts]
二叉树遍历。遍历过程中累加节点值,当到达任意叶节点的时候,进行判断。
[Code]
1: bool hasPathSum(TreeNode *root, int sum) {
2: return hasPathSum(root, 0, sum);
3: }
4: bool hasPathSum(TreeNode *root, int sum, int target) {
5: if(root == NULL) return false;
6: sum += root->val;
7: if(root->left == NULL && root->right == NULL) //leaf
8: {
9: if(sum == target)
10: return true;
11: else
12: return false;
13: }
14: return hasPathSum(root->left, sum, target)
15: || hasPathSum(root->right, sum, target);
16: }
本文探讨了一道经典的二叉树遍历问题:给定一棵二叉树及一个目标和,判断是否存在从根节点到叶子节点的路径,使得路径上所有节点值之和等于给定的目标和。通过递归方法解决此问题。
5914

被折叠的 条评论
为什么被折叠?



