leetcode112題 題解 翻譯 C語言版 Python版
阿新 • • 發佈:2019-01-03
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
思路:這題用遞迴很方便就能解決。如果當前是葉結點,那麼只需要判斷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