letecode [112] - Path Sum
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.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
/ \
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.
题目大意:
给定二叉树,判断是否存在某条路径从根节点到叶节点,所有节点元素的和等于给定值。
理解:
遍历二叉树,每遍历到叶节点则判断是否等于给定值。
遍历时,给定值动态变化,每遍历某个节点,递归遍历它的子节点时,用总和-该节点值。
直接用==结果作为返回值。
代码C++:
/** * Definition for a binary tree node. * 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==NULL) return false; int val = root->val; bool res = false; if(root->left==NULL && root->right==NULL){ return root->val == sum; } if(root->left!=NULL) res = hasPathSum(root->left,sum-val); if(root->right!=NULL) res = res|hasPathSum(root->right,sum-val); return res; } };
运行结果:
执行用时 : 16 ms 内存消耗 : 19.9 MB