[LeetCode] Path Sum 二叉树的路径和
2014-10-20 13:08
141 查看
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
这道求二叉树的路径需要用深度优先算法DFS的思想来遍历每一条完整的路径,也就是利用递归不停找子节点的左右子节点,而调用递归函数的参数只有当前节点和sum值。首先,如果输入的是一个空节点,则直接返回false,如果如果输入的只有一个根节点,则比较当前根节点的值和参数sum值是否相同,若相同,返回true,否则false。 这个条件也是递归的终止条件。下面我们就要开始递归了,由于函数的返回值是Ture/False,我们可以同时两个方向一起递归,中间用或||连接,只要有一个是True,整个结果就是True。递归左右节点时,这时候的sum值应该是原sum值减去当前节点的值。代码如下:
LeetCode All in One 题目讲解汇总(持续更新中...)
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.
这道求二叉树的路径需要用深度优先算法DFS的思想来遍历每一条完整的路径,也就是利用递归不停找子节点的左右子节点,而调用递归函数的参数只有当前节点和sum值。首先,如果输入的是一个空节点,则直接返回false,如果如果输入的只有一个根节点,则比较当前根节点的值和参数sum值是否相同,若相同,返回true,否则false。 这个条件也是递归的终止条件。下面我们就要开始递归了,由于函数的返回值是Ture/False,我们可以同时两个方向一起递归,中间用或||连接,只要有一个是True,整个结果就是True。递归左右节点时,这时候的sum值应该是原sum值减去当前节点的值。代码如下:
/** * 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 == NULL) return false; if (root->left == NULL && root->right == NULL && root->val == sum ) return true; return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } };
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- [LeetCode] Path Sum 求二叉树中满足要求的路径
- [LeetCode] Path Sum 求二叉树中满足要求的路径
- LeetCode 64. Minimum Path Sum(最小路径和)
- LeetCode Path Sum 判断树的路径之和
- LeetCode (12) Path Sum (二叉树路径和判断)
- 【Leetcode】二叉树简单路径最大和问题
- 【Leetcode】二叉树简单路径最大和问题
- 二叉树系列 - 二叉树里的最长路径 例 [LeetCode] Binary Tree Maximum Path Sum
- leetCode 112 二叉树路径求和问题
- 【LeetCode】Path Sum 2 --java 二叉数 深度遍历,保存路径
- [LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- leetcode Sum Root to Leaf Numbers 二叉树所有叶节点的路径和
- [LeetCode] Binary Tree Paths 二叉树路径
- <LeetCode><Easy> 112 Path Sum --二叉树深度优先遍历
- LeetCode---- 二叉树中,找出和为某值的所有路径
- Path Sum 二叉树路径和 @LeetCode
- [leetcode] Path sum路径之和
- LeetCode-Binary Tree Maximum Path Sum-二叉树最大路径和-DFS