重建二叉树

根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

NowCoder

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.HashMap;
 
public class Solution {
    //private Map<Integer, Integer> inOrderNumberIndex = new HashMap<>();
    HashMap<Integer, Integer> inOrderNumberIndex = new HashMap<Integer, Integer>();
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        for (int i = 0; i < in.length; i++) {
            inOrderNumberIndex.put(in[i], i);
        }
        return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
    }
    private TreeNode reConstructBinaryTree(int [] pre,int preL, int preR,
                                           int [] in, int inL, int inR) {
        if (preL > preR) {
            return null;
        }
        TreeNode root = new TreeNode(pre[preL]);
        int leftChildSize = inOrderNumberIndex.get(pre[preL]) - inL;
        root.left = reConstructBinaryTree(pre, preL + 1, preL + leftChildSize,
                                         in, inL, inL + leftChildSize - 1);
        root.right = reConstructBinaryTree(pre, preL + leftChildSize + 1, preR,
                                          in, inL + leftChildSize + 1, inR);
        return root;
    }
}
comments powered by Disqus