105 从前序与中序遍历序列构造二叉树
import java. util. HashMap ;
import java. util. Map ; class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode ( int val) { this . val = val; }
} public class Letcode105 { public TreeNode bulidTree ( int [ ] preOrder, int [ ] inOrder) { int preLength = preOrder. length; int inLength = inOrder. length; Map < Integer , Integer > map = new HashMap < > ( ) ; for ( int i = 0 ; i < inLength; i++ ) { map. put ( inOrder[ i] , i) ; } return bulidTree ( preOrder, 0 , preLength - 1 , map, 0 , inLength - 1 ) ; } private TreeNode bulidTree ( int [ ] preOrder, int preLeft, int preRight, Map < Integer , Integer > map, int inLeft, int inRight) { if ( preLeft > preRight || inLeft > inRight) { return null ; } int root = preOrder[ preLeft] ; TreeNode treeNode = new TreeNode ( root) ; int pIndex = map. get ( root) ; treeNode. left = bulidTree ( preOrder, preLeft + 1 , pIndex - inLeft + preLeft, map, inLeft, pIndex - 1 ) ; treeNode. right = bulidTree ( preOrder, pIndex - inLeft + preLeft + 1 , preRight, map, pIndex + 1 , inRight) ; return treeNode; }
}