题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
func reConstructBinaryTree( pre []int , vin []int ) *TreeNode {
// write code here
if length := len(pre); length == 0 {
return nil
}
i := 0
for i = 0; i < len(vin); i++ {
if vin[i] == pre[0] {
break
}
}
root := &TreeNode{pre[0], nil, nil}
root.Left = reConstructBinaryTree(pre[1:i+1], vin[:i])
root.Right = reConstructBinaryTree(pre[i+1:], vin[i+1:])
return root
}
算法思想:假定pre的第一个在vin的位置为i,则vin[:i]是结点val为vin[i]的左子树;vin[:i+1]是右子树