105. 从前序与中序遍历序列构造二叉树
class Solution { HashMap inhm = new HashMap(); public TreeNode buildTree(int[] preorder, int[] inorder) { inhm.clear(); for(int i = 0 ; i<preorder.length;i++) { inhm.put(inorder[i], i); } int n = preorder.length; return dfs(preorder, inorder , 0,n-1 , 0 , n-1); } public TreeNode dfs(int[]preorder,int[]inorder,int pl , int pr , int il ,int ir) { if(pl>pr)return null; TreeNode root = new TreeNode(preorder[pl]); int k = inhm.get(preorder[pl]); int len = k - il; root.left = dfs(preorder , inorder , pl+1 ,pl+len ,il ,k-1 ); root.right = dfs(preorder , inorder , pl+len+1, pr, k+1, ir); return root; } }
自己写的
class Solution { int index = 0; public TreeNode buildTree(int[] preorder, int[] inorder) { return createBuild(preorder,inorder,0,preorder.length-1); } public TreeNode createBuild(int []preorder,int[]inorder,int start ,int end){ if(start>end)return null; int val = preorder[index++]; TreeNode root = new TreeNode(val); for (int i = 0; i < inorder.length; i++) { if(inorder[i]==val){ root.left = createBuild(preorder,inorder,start ,i-1); root.right = createBuild(preorder,inorder,i+1 , end); break; } } return root; } }