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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jan 28 - Construct Binary Tree From Preorder And Inorder; Tree; DFS; Array相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

606. Construct String from Binary Tree

Jan 27 - Valid Binary Search Tree; DFS;

606. Construct String from Binary Tree

[Leetcode] Binary tree-- 606. Construct String from Binary Tree

LeetCode Construct String from Binary Tree

Construct String From Binary Tree