您的位置:首页 > 编程语言 > C语言/C++

leetcode112题 题解 翻译 C语言版 Python版

2016-04-19 15:05 169 查看


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.
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.

112.路径和

给定一棵二叉树和一个和,确定这棵树是否有一个从根到叶的路径使得路径上结点值加起来等于这个给定的和。

例如:

给定下面这棵二叉树并且给定和sum=22

5
/ \
4   8
/   / \
11  13  4
/  \      \
7    2      1

返回true,因为存在这么条路径5->4->11->2且其和为22

思路:这题用递归很方便就能解决。如果当前是叶结点,那么只需要判断sum是否等于当前叶结点的值。如果当前不是叶节点,那么我用sum减去当前结点的值,然后递归地去判断两棵子树有没有可以满足这个值的。只要有一棵子树能满足,那么层层返回,最后就能满足。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
bool hasPathSum(struct TreeNode* root, int sum) {
if (!root) return false;
if (!root->left && !root->right) return root->val == sum;
bool flagl = false, flagr = false;
if (root->left) flagl = hasPathSum(root->left, sum - root->val);
if (root->right) flagr = hasPathSum(root->right, sum - root->val);
return flagl || flagr;
}


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
if not (root.left or root.right): return root.val == sum
flagl, flagr = False, False
if root.left: flagl = self.hasPathSum(root.left, sum - root.val)
if root.right: flagr = self.hasPathSum(root.right, sum - root.val)
return flagl or flagr


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: