题目:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
思路:
递归,主要是找边界条件,找好之后并不难。
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {     public TreeNode reConstructBinaryTree(int[] pre,int[] in) {         return re(pre,0,pre.length-1,in,0,in.length-1);     }     public TreeNode re(int[] pre,int l1,int r1,int[] in,int l2,int r2) {         if (r1<l1||r2<l2) {             return null;         }         TreeNode root = new TreeNode(pre[l1]);         for (int i=l2; i<=r2; i++) {             if (in[i]==pre[l1]) {                 root.left=re(pre,l1+1,l1+i-l2,in,l2,i-1);                 root.right=re(pre,l1+i-l2+1,r1,in,i+1,r2);             }         }         return root;     }
}