题目描述:
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:3
/ \
9 20
/ \
15 7
解题思路:
递归,利用中序和后序遍历二叉树的特点,后序遍历最末尾为根节点,找到根节点在中序遍历对应位置,以此为分界线,左侧为左子树节点集合,右侧为右子树节点集合
我的写法:
func buildTree(inorder []int, postorder []int) *TreeNode {
var treeBuild = new(TreeNode)
if len(inorder) == 0 || len(postorder) == 0{
return nil
}
treeBuild.Val = postorder[len(postorder)-1]
if len(inorder) == 1 || len(postorder) == 1{
return treeBuild
}
for i,v :=range inorder{
if v == postorder[len(postorder)-1]{
treeBuild.Left = buildTree(inorder[:i],postorder[:i])
treeBuild.Right = buildTree(inorder[i+1:],postorder[i:len(postorder)-1])
}
}
return treeBuild
}
官方写法:
func buildTree(inorder []int, postorder []int) *TreeNode {
idxMap := map[int]int{}
for i, v := range inorder {
idxMap[v] = i
}
var build func(int, int) *TreeNode
build = func(inorderLeft, inorderRight int) *TreeNode {
// 无剩余节点
if inorderLeft > inorderRight {
return nil
}
// 后序遍历的末尾元素即为当前子树的根节点
val := postorder[len(postorder)-1]
postorder = postorder[:len(postorder)-1]
root := &TreeNode{Val: val}
// 根据 val 在中序遍历的位置,将中序遍历划分成左右两颗子树
// 由于我们每次都从后序遍历的末尾取元素,所以要先遍历右子树再遍历左子树
inorderRootIndex := idxMap[val]
root.Right = build(inorderRootIndex+1, inorderRight)
root.Left = build(inorderLeft, inorderRootIndex-1)
return root
}
return build(0, len(inorder)-1)
}
复杂度分析
时间复杂度:O(n),其中 nn 是树中的节点个数。
空间复杂度:O(n)。我们需要使用 O(n) 的空间存储哈希表,以及 O(h)(其中 hh 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为 O(n)。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/cong-zhong-xu-yu-hou-xu-bian-li-xu-lie-gou-zao-14/