【剑指OFFER】重建二叉树
【题目描述】
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
时间限制:1秒 空间限制:32768K
【AC代码】
Reference: https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6?f=discussion

1 public class Solution { 2 public TreeNode reConstructBinaryTree(int [] pre,int [] in) { 3 TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1); 4 return root; 5 } 6 private TreeNode reConstructBinaryTree(int [] pre, int startPre, int endPre, int [] in, int startIn, int endIn) { 7 if (startPre > endPre || startIn > endIn) return null; //验证子树是否整理完毕 8 TreeNode root = new TreeNode(pre[startPre]); //每颗子树的根节点肯定是pre子数组的首元素,所以每次新建一个子树的根节点。 9 //根据中序遍历找到左子树和右子树的长度 10 for (int i = startIn; i <= endIn; i++) { 11 if (in[i] == root.val) { 12 //利用递归思想,每次将左右子树当成新二叉树进行处理。 13 //(i-startIn)指中序根节点i与前序起点startIn之间的左孩子长度 14 root.left = reConstructBinaryTree(pre, startPre+1, startPre+(i-startIn), in, startIn, i-1); 15 root.right = reConstructBinaryTree(pre, startPre+(i-startIn)+1, endPre, in, i+1, endIn); 16 break; 17 } 18 } 19 return root; 20 } 21 }