使用层次遍历迭代的思路
# 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
#使用层次遍历迭代
if root is None:
return 0
que = deque()
que.append(root)
res = 0
while que:
size = len(que)
for i in range(size):
cur = que.popleft()
if i == 0:
res = cur.val
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
return res
直接判断孩子节点的数值,方便回溯
# 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 travelsal(self, node, cnt):
if node.left is None and node.right is None and cnt == 0:
return True
if node.left is None and node.right is None:
return False
if node.left:
cnt -= node.left.val #为了回溯,直接判断孩子节点的值
if self.travelsal(node.left, cnt):
return True
cnt += node.left.val
if node.right:
cnt -= node.right.val
if self.travelsal(node.right,cnt):
return True
cnt += node.right.val
return False
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
return self.travelsal(root, targetSum - root.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 travelsal(self, node, path, cnt, res):
if node is None:
return
cnt -= node.val
path.append(node.val)
if node.left is None and node.right is None and cnt == 0:
res.append(path[:])
self.travelsal(node.left, path, cnt, res)
self.travelsal(node.right, path, cnt, res)
path.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res = []
if root is None:
return []
self.travelsal(root, [], targetSum, res)
return res
很多细节,要注意!
# 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 buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder:
return None
root_val = postorder[-1]
root = TreeNode(root_val)
sep_index = inorder.index(root_val)
inorder_left = inorder[:sep_index]
inorder_right = inorder[sep_index+1:]
left_size = len(inorder_left)
postorder_left = postorder[:left_size]
postorder_right = postorder[left_size:-1]
root.left = self.buildTree(inorder_left, postorder_left)
root.right = self.buildTree(inorder_right, postorder_right)
return root