原文链接 [每日 LeetCode] 112. Path Sum
Description:
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** 3 4 / \ \ 7 **2** 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
思路:本题要求判断树中是否存在某个和为 sum 的路径,有则返回 true,否则返回 false。依旧使用递归思想,如果当前结点没有子结点,比较当前结点的值和 sum 值,如果当前结点存在子结点,比较当前结点的子结点值是否等于 sum-当前结点值,依次从左到右进行比较。
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) return false; if(!root->left && !root->right) return sum == root->val; return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } };
运行时间:16ms
运行内存:20.1M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于