LeetCode:
106 中序和后序遍历确定二叉树
105 前序和中序遍历确定二叉树
根据一棵树的中序遍历与后序遍历构造二叉树
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
二叉树遍历
二叉树的前序、中序、后序遍历(深度优先遍历)
遍历即将树的所有结点都访问且仅访问一次。按照根结点访问次序的不同,可以分为前序遍历,中序遍历,后序遍历。
前序遍历:根结点 -> 左子树 -> 右子树
中序遍历:左子树 -> 根结点 -> 右子树
后序遍历:左子树 -> 右子树 -> 根结点
思路:递归思想root --> root.left + root.right
中序+后序确定二叉树:后序遍历的最后一个节点为root, 中序遍历中的root将二叉树划分为左、右子树,对于左右子树同样处理:递归
前序+中序确定二叉树:前序遍历的第一个节点为root, 中序遍历中的root将二叉树划分为左、右子树,对于左右子树同样处理:递归
定义二叉树:
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
中序+后序确定二叉树实现:
class Solution:
# 根据 中序+后序
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if len(postorder)==0: return None
if len(postorder)==1: return TreeNode(postorder[0])
else:
value = postorder[len(postorder)-1]
root=TreeNode(value)
index = inorder.index(value)
root.left=self.buildTree(inorder[:index], postorder[:index])
root.right=self.buildTree((inorder[index+1:], postorder[index:len(postorder)-1]))
return root
前序+中序确定二叉树实现:
# 根据 前序+中序
def buildTree2(self,preorder:List[int],inorder:List[int]):
if len(preorder)==0: return None
if len(preorder)==0: return TreeNode(preorder[0])
else:
value=preorder[0]
root=TreeNode(value)
index=inorder.index(value)
root.left=self.buildTree2(preorder[1:index+1],inorder[:index])
root.right=self.buildTree2(preorder[index+1:],inorder[index+1:])
return root
测试代码:
if __name__ =="__main__":
s=Solution()
inorder =[9, 3, 15, 20, 7]
postorder =[9, 15, 7, 20, 3]
r=s.buildTree()