/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{privateMap<Integer,Integer>d=newHashMap<>();privateint[]preorder;privateint[]inorder;publicTreeNodebuildTree(int[]preorder,int[]inorder){intn=inorder.length;for(inti=0;i<n;++i){d.put(inorder[i],i);}this.preorder=preorder;this.inorder=inorder;returndfs(0,0,n);}privateTreeNodedfs(inti,intj,intn){if(n<1){returnnull;}intk=d.get(preorder[i]);intl=k-j;TreeNoderoot=newTreeNode(preorder[i]);root.left=dfs(i+1,j,l);root.right=dfs(i+1+l,k+1,n-l-1);returnroot;}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcbuildTree(preorder[]int,inorder[]int)*TreeNode{d:=map[int]int{}fori,v:=rangeinorder{d[v]=i}vardfsfunc(i,j,nint)*TreeNodedfs=func(i,j,nint)*TreeNode{ifn<1{returnnil}k:=d[preorder[i]]l:=k-jroot:=&TreeNode{Val:preorder[i]}root.Left=dfs(i+1,j,l)root.Right=dfs(i+1+l,k+1,n-l-1)returnroot}returndfs(0,0,len(inorder))}
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * @param {number[]} preorder * @param {number[]} inorder * @return {TreeNode} */varbuildTree=function(preorder,inorder){constd=newMap();constn=inorder.length;for(leti=0;i<n;++i){d.set(inorder[i],i);}constdfs=(i,j,n)=>{if(n<1){returnnull;}constk=d.get(preorder[i]);constl=k-j;constroot=newTreeNode(preorder[i]);root.left=dfs(i+1,j,l);root.right=dfs(i+1+l,k+1,n-l-1);returnroot;};returndfs(0,0,n);};
1 2 3 4 5 6 7 8 9101112131415161718192021
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */publicclassSolution{publicTreeNodeBuildTree(int[]preorder,int[]inorder){if(preorder.Length==0){returnnull;}TreeNoderoot=newTreeNode(preorder[0]);intidx=Array.IndexOf(inorder,root.val);root.left=BuildTree(preorder[1..(index+1)],inorder[0..idx]);root.right=BuildTree(preorder[(index+1)..],inorder[(idx+1)..]);returnroot;}}
/* public class TreeNode {* public var val: Int* public var left: TreeNode?* public var right: TreeNode?* public init(_ val: Int) {* self.val = val* self.left = nil* self.right = nil* }* }*/classSolution{privatevard=[Int:Int]()privatevarpreorder:[Int]=[]privatevarinorder:[Int]=[]funcbuildTree(_preorder:[Int],_inorder:[Int])->TreeNode?{letn=inorder.countforiin0..<n{d[inorder[i]]=i}self.preorder=preorderself.inorder=inorderreturndfs(0,0,n)}privatefuncdfs(_i:Int,_j:Int,_n:Int)->TreeNode?{ifn<1{returnnil}letk=d[preorder[i]]!letl=k-jletroot=TreeNode(preorder[i])root.left=dfs(i+1,j,l)root.right=dfs(i+1+l,k+1,n-l-1)returnroot}}