Tree:前序、中序构建二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder==null||inorder==null||preorder.length==0||inorder.length==0||preorder.length!=inorder.length) {
            return null;
        }
        HashMap hashMap = new HashMap();
        for (int i = 0; i < inorder.length; i++) {
            hashMap.put(inorder[i], i);
        }
        return getNode(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1, hashMap);
    }
    private TreeNode getNode(int[] pre,int pi,int pj,int[] in,int ni,int nj,HashMap hashMap) {
        if (pi>pj) {
            return null;
        }
        int index = hashMap.get(pre[pi]);
        TreeNode node = new TreeNode(pre[pi]);
        node.left = getNode(pre, pi+1, pi+index-ni, in, ni, index-1, hashMap);
        node.right = getNode(pre, pi+index-ni+1, pj, in, index+1, nj, hashMap);
        return node;
    }
}

你可能感兴趣的:(Tree:前序、中序构建二叉树)