由前序和后序构建任一符合的二叉树
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func constructFromPrePost(preorder []int, postorder []int) *TreeNode { return build(preorder,0,len(preorder)-1,postorder,0,len(postorder)-1) } func build(preorder []int,s1,e1 int,postorder []int,s2,e2 int)*TreeNode{ if s1>e1{ return nil } if s1==e1{ return &TreeNode{preorder[s1],nil,nil} } //根节点是前序遍历的第一个 rootVal:=preorder[s1] //选择前序遍历的第二个点作为左子树的根节点 leftVal:=preorder[s1+1] //在后序遍历查找左子树根节点的索引 idx:=s2 for i:=s2;i<e2;i++{ if postorder[i]==leftVal{ idx=i break } } //构造根节点 root:=&TreeNode{} root.Val=rootVal //递归构造左右节点 leftSize:=idx-s2+1 root.Left=build(preorder,s1+1,s1+leftSize,postorder,s2,idx) root.Right=build(preorder,s1+leftSize+1,e1,postorder,idx+1,e2-1) return root }