题解 | #重建二叉树#

重建二叉树

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]是右子树
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 13:15
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务