一:题目
二:上码
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public TreeNode getTree(int leftIn,int rightIn,int leftPre,int rightPre,int[] pre,int[] in) {if (leftIn > rightIn) return null;//求取根节点在中序数组中的下标int rootIn = leftIn;while (rootIn <= rightIn && pre[leftPre] != in[rootIn]) rootIn++;//求取左子树的个数int leftNums = rootIn - leftIn;TreeNode root = new TreeNode(pre[leftPre]);root.left = getTree(leftIn,rootIn-1,leftPre+1,(leftPre+1)+leftNums - 1,pre,in);root.right = getTree(rootIn+1,rightIn,(leftPre+1)+leftNums,rightPre,pre,in);return root;}public TreeNode buildTree(int[] preorder, int[] inorder) {return getTree(0,inorder.length-1,0,preorder.length-1,preorder,inorder);}
}