Jan 28 - Construct Binary Tree From Inorder And Postorder; Tree; DFS; Array;

Same idea of the former problem, only difference is that the root is located in the last position of postorder array. And the left child is in pos-(end-inorderPos) and right child is in pos: pos-1 in postorder array.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    Map<Integer, Integer> inorderMap = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len = preorder.length;
        if(len == 0) return null;
        
        for(int i = 0; i < len; i++) inorderMap.put(inorder[i], i);
        
        return dfsAddNode(preorder, inorder, -1, len, 0);
        
    }
    
    public TreeNode dfsAddNode(int[] preorder, int[] inorder, int start, int end, int preorderPos){
        int val = preorder[preorderPos];
        TreeNode node = new TreeNode(val);
        int inorderPos = inorderMap.get(val);
        //int inorderPos = -1;
        /*
        for(int i = start+1; i < end; i++){
            if(inorder[i] == val) inorderPos = i;
        }
        */
        
        if(inorderPos == start+1) node.left = null;
        else node.left = dfsAddNode(preorder, inorder, start, inorderPos, preorderPos+1);
        if(inorderPos == end-1) node.right = null;
        else node.right = dfsAddNode(preorder, inorder, inorderPos, end, preorderPos+inorderPos-start);
        
        return node;
    }
    /*
    public int inorderPos(int[] inorder, int start, int end, int val){
        for(int i = start+1; i < end; i++){
            if(inorder[i] == val) return i;
        }
        return -1;
    }
    */
}

 

你可能感兴趣的:(Jan 28 - Construct Binary Tree From Inorder And Postorder; Tree; DFS; Array;)