中序遍历:左中右 后序遍历:左右中
#lc105. 从前序与中序遍历序列构造二叉树
# 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, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder:
return#此处不能return []
node_val=preorder[0]
root=TreeNode(node_val)
idx=inorder.index(node_val)
inorder_left=inorder[:idx]
inorder_right=inorder[idx+1:]
preorder_left=preorder[1:len(inorder_left)+1]
preorder_right=preorder[len(inorder_left)+1:]
root.left=self.buildTree(preorder_left,inorder_left)##此处要加上root.left
root.right=self.buildTree(preorder_right,inorder_right)##此处要加上root.right
return root
# lc106 从中序和后序构造二叉树
#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
node_val=postorder[-1]
root=TreeNode(node_val)
node_idx=inorder.index(node_val)
inorder_left=inorder[:node_idx]
inorder_right=inorder[node_idx+1:]
postorder_left=postorder[:node_idx]
postorder_right=postorder[node_idx:-1]
root.left=self.buildTree(inorder_left,postorder_left)
root.right=self.buildTree(inorder_right, postorder_right)
return root
#513 找树左下角的值
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:#【二轮】使用递归法
if not root:
return
st=[root]
# results=[]
while st:
result=[]
n=len(st)
for i in range(n):
node=st.pop(0)
result.append(node.val)
if node.left:
st.append(node.left)
if node.right:
st.append(node.right)
return result[0]
#112 路径总和
#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 False
st=[(root,root.val)]
while st:
cur_node, sum_=st.pop(0)
if not cur_node.left and not cur_node.right and targetSum==sum_:
return True
if cur_node.left:
st.append((cur_node.left, sum_+cur_node.left.val))
if cur_node.right:
st.append((cur_node.right, sum_+cur_node.right.val))
return False
#113路径总和②
# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:#【二轮】使用递归法
if not root:
return []
result=[]
st=[root]
tmp=[(root.val,[root.val])]
while st:
n=len(st)
for _ in range(n):
node=st.pop(0)
value,path=tmp.pop(0)
if not node.left and not node.right:
if sum(path)==targetSum:
result.append(path)
if node.left:
st.append(node.left)
tmp.append((value+node.left.val,path+[node.left.val]))
if node.right:
st.append(node.right)
tmp.append((value+node.right.val,path+[node.right.val]))
return result