Using DFS to traverse the node and build the a tree. for a node, it has following properties:

If its a left child node of its parent, then the left boundary start of in the inorder array is its parent's location in inorder array. Let inorderPos be the location of current node, we can find it in the left part of parent node pos in inorder array. if inorderPos == start+1, this means current node has no left child, set it to be null. Otherwise, it has a left child node, and the postion of its left child node is preorderPos+1 in preorderPos array. Then we can go into its left child, update end to be current node's in-order pos. If inorderPos == end - 1; it means current node has no right child, set it to be null. Otherwise, it has a right child node, and the position of its right node is preorderPos+inorderPos-start, update start to be current node's in-order pos.

Code:

/**
 * 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) {
        int len = preorder.length;
        if(len == 0) return null;
        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 = -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;
    }
    */
}

 A little advance is that, we can use a hashmap to record the postion of inorder element. To avoid unnecessay duplicative look through in the inorder array.

posted on 2016-01-29 06:20  爱推理的骑士  阅读(131)  评论(0编辑  收藏  举报