由前序遍历和中序遍历构造二叉树
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func buildTree(preorder []int, inorder []int) *TreeNode { return build(preorder,0,len(preorder)-1,inorder,0,len(inorder)-1) } func build(preorder []int,s1,e1 int,inorder []int,s2,e2 int)*TreeNode{ if s1>e1{ return nil } // root 节点对应的值就是前序遍历数组的第⼀个元素 rootVal:=preorder[s1] // rootVal 在中序遍历数组中的索引 inIdx:=s2 for i:=s2;i<e2;i++{ if inorder[i]==rootVal{ inIdx=i break } } root:=&TreeNode{} root.Val=rootVal // 递归构造左右⼦树 leftSize:=inIdx-s2//左子树节点个数 root.Left=build(preorder,s1+1,s1+leftSize,inorder,s2,inIdx-1) root.Right=build(preorder,s1+leftSize+1,e1,inorder,inIdx+1,e2) return root }