码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-01-29 08:42:46      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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.

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

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5167922.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!