480 · Binary Tree Paths
Description
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Contact me on wechat to get Amazon、Google requent Interview questions . (wechat id : jiuzhang0607)
Example
Example 1:
Input:
tree = {1,2,3}
Output:
true
Explanation:
This is a balanced binary tree.
1
/ \
2 3
Example 2:
Input:
tree = {1,#,2,3,4}
Output:
false
Explanation:
This is not a balanced tree.
The height of node 1's right sub-tree is 2 but left sub-tree is 0.
1
\
2
/ \
3 4
对于此类问题应该思考从当前层向下面的左右子树要什么。我们需要的是左右子树分别的路径,然后在他们前面加上本层节点
from typing import (
List,
)
from lintcode import (
TreeNode,
)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
we will sort your return value in output
"""
def binary_tree_paths(self, root: TreeNode) -> List[str]:
# write your code here
if not root:
return []
if not root.left and not root.right:
return [str(root.val)] #change it to string
ll = self.binary_tree_paths(root.left)
rr = self.binary_tree_paths(root.right)
res = []
for s in ll+rr:
res.append(str(root.val)+'->'+s)
return res
112. Path Sum
Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown.
Example 2:
Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5.
Example 3:
Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths.
Constraints:
- The number of nodes in the tree is in the range
[0, 5000]
. -1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
和上面的题一样,对于一个节点,它需要的是左右子树返回的结果,返回到了叶子节点是否正好等于targetsum,我们就可以在往下走的时候每次减去当前节点的val,看剩下的子路径和是否相等
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return
if not root.left and not root.right:
if root.val == targetSum:
return True
else:
return False
l = self.hasPathSum(root.left,targetSum-root.val)
r = self.hasPathSum(root.right,targetSum-root.val)
return l or r