題目

輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請重建該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復(fù)的數(shù)字。

例如,給出

前序遍歷 preorder = [3,9,20,15,7]中序遍歷 inorder = [9,3,15,20,7]返回如下的二叉樹:
    3   / /  9  20    /  /   15   7

限制:

0 <= 節(jié)點個數(shù) <= 5000

答案

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public TreeNode buildTree(int[] preorder, int[] inorder) {        int n = preorder.length;        if (n == 0)            return null;        int rootVal=preorder[0],rootIndex=0;        for(int i=0;i