题解 | #重建二叉树#

重建二叉树

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

相关推荐

09-22 09:42
门头沟学院 Java
牛客37185681...:马德,我感觉这是我面过最恶心的公司,一面是两个女hr,说什么实习前几个月属于试用期,试用期过了才能转成正式实习生,我***笑了,问待遇就是不说,问能不能接受全栈,沙币公司
如果可以选,你最想去哪家...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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