该题目来源于牛客网《剑指offer》专题。
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
Go语言实现:
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func reConstructBinaryTree(pre, mid []int) *TreeNode {
root := reConstructBinaryTreeHandler(pre, 0, len(pre)-1, mid, 0, len(mid)-1)
return root
}
func reConstructBinaryTreeHandler(pre []int, pStart, pEnd int, mid []int, mStart, mEnd int, ) *TreeNode {
//叶子结点,没有子树
if pStart > pEnd || mStart > mEnd {
return nil
}
//跟结点
root := new(TreeNode)
root.Val = pre[pStart]
//左右子树
for i := mStart; i <= mEnd; i++ {
if mid[i] == pre[pStart] {
//前序遍历{1,2,4,7,3,5,6,8} 中序遍历序列{4,7,2,1,5,3,8,6}
//247:pre[pStart+1]=2,pre[pStart+3-0]=7;472:mid[mStart]=4,mid[i-1]=2
root.Left = reConstructBinaryTreeHandler(pre, pStart+1, pStart+i-mStart, mid, mStart, i-1)
//3568:pre[pStart+i+1-mStart]=3,pre[pEnd]=8;5386:mid[i+1]=5,mid[mEnd]=6
root.Right = reConstructBinaryTreeHandler(pre, pStart+i+1-mStart, pEnd, mid, i+1, mEnd)
//分完左右,退出循环
break
}
}
return root
}