根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
python
# 0106.中序后序构造二叉树
class Solution:
def buildTree(self, inorder: [int], postorder: [int]) -> TreeNode:
# 1.递归终止条件
if not postorder:
return None
# 2.后序最后元素为当前中间节点
rootVal = postorder[-1]
root = TreeNode(rootVal)
# 3.找切割点
sepIndex = inorder.index(rootVal)
# 4.切割inorder数组,得到inorder的左右半边
inorderLeft = inorder[:sepIndex]
inorderRight = inorder[sepIndex+1:]
# 5.切割postorder数组,得到postorder数组的左右半边
postorderLeft = postorder[:len(inorderLeft)]
postorderRight = postorder[len(inorderLeft):len(postorder)-1]
# 6.递归左右半边
root.left = self.buildTree(inorderLeft, postorderLeft)
root.right = self.buildTree(inorderRight, postorderRight)
return root
# 0105.前序中序构造二叉树
class Solution:
def buildTree(self, preorder: [int], inorder: [int]) -> TreeNode:
# 1.递归终止条件
if not preorder:
return None
# 2.前序第一个为当前中间节点
rootVal = preorder[0]
root = TreeNode(rootVal)
# 3.找切割点
sepIndex = inorder.index(rootVal)
# 4.切割inorder数组,得左右半边
inorderLeft = inorder[:sepIndex]
inorderRight = inorder[sepIndex+1:]
# 5.切割preorder数组,得左右半边
pretorderLeft = preorder[1:1+len(inorderLeft)]
pretorderRight = preorder[1+len(inorderLeft):]
# 6.递归
root.left = self.buildTree(pretorderLeft, inorderLeft)
root.right = self.buildTree(pretorderRight, inorderRight)
return root
golang
package binaryTree
// 0106.中后序构造二叉树
func buildTree1(inorder []int, postorder []int) *TreeNode {
// 1.递归终止条件
if len(inorder) < 1 || len(postorder) < 1 {
return nil
}
// 2.找到当前中间节点
nodeVal := postorder[len(postorder)-1]
// 3.找到切割点
left := findRootIndex(inorder, nodeVal)
// 4.构造root
root := &TreeNode{Val: nodeVal,
Left: buildTree1(inorder[:left], postorder[:left]),
Right: buildTree1(inorder[left+1:], postorder[left:len(postorder)-1])}
return root
}
func findRootIndex(inorder []int, targetVal int) int {
for i,v := range inorder {
if targetVal == v {
return i
}
}
return -1
}
// 105.前中序构造二叉树
func buildTree2(preorder []int, inorder []int) *TreeNode {
// 1.递归终止条件
if len(preorder) < 1 || len(inorder) < 1 {
return nil
}
// 2.找当前中间点值
nodeVal := preorder[0]
// 3.找切割位置
left := findRootIndex(inorder, nodeVal)
// 4.构造root
root := &TreeNode{
Val: nodeVal,
Left: buildTree2(preorder[1:left+1], inorder[:left]),
Right: buildTree2(preorder[left+1:], inorder[left+1:])
}
return root
}