112. Path Sum*
https://leetcode.com/problems/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
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
C++ 实现 1
思路是, 由于是从根节点到叶子节点的路径, 所以当根节点的值(假设为 val) 不等于 sum 的时候, 那么就希望以左孩子或右孩子为根节点的子树中存在某路径使得节点之和等于 sum - val, 只要不断递归到叶子节点即可. 注意递归到底的情况, 当根节点为 NULL, 那么当然返回 false. 而当根节点不为空, 需要满足它没有左右子节点并且值等于 sum, 才能返回 true.
/**
* 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) return false;
if (!root->left && !root->right) return root->val == sum;
return hasPathSum(root->left, sum - root->val) ||
hasPathSum(root->right, sum - root->val);
}
};
珍妮的选择
发布了327 篇原创文章 · 获赞 7 · 访问量 1万+
私信
关注