Construct Binary Tree from Preorder and Inorder Traversal

Fair Construct Binary Tree from Preorder and Inorder TraversalMy Submissions

35%
Accepted

Given preorder and inorder traversal of a tree, construct the binary tree.

Note

You may assume that duplicates do not exist in the tree.

IDEA: RECURSION 



WRONG IDEA:

root.left = helper(inorder, in_start, pos - 1, preorder, p_start + 1);

root.right = helper(inorder, pos + 1, in_end, preorder, p_start + 1);

REASON: NOT THE SAME PROBLEM. For preorder traversal, we visit root first, and then the left subTree, and then the right subTree, so the root node for the right subtree cannot be p_start   + 1. It must be the actual root node for the right subtree. How can we know the index of the root node of the right subtree?

WE CALCULATE THE LOCATION FROM INORDER ARRAY.

1. we can find the root node for the current level in the inorder array

2. the elements on the right of the root belong to the right subtree. Now we can know how many elements are in the tree

3. We can subtract the number of elements in the right subtree from the current level root node. 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        if (preorder == null || inorder == null || preorder.length != inorder.length) {
            return null;
        }
        return helper(inorder, 0, inorder.length - 1, preorder, 0, preorder.length - 1);
        
    }
    
    TreeNode helper(int[] inorder, int in_start, int in_end, 
        int[] preorder, int p_start, int p_end) {
            if(in_start > in_end) {
                return null;
            }
            int key = preorder[p_start];
            TreeNode node = new TreeNode(key);
            int pos = findRoot(inorder, in_start, in_end, key);
            node.left = helper(inorder, in_start, pos - 1, 
                preorder, p_start + 1, p_start + pos - in_start);
            node.right = helper(inorder, pos + 1, in_end,
                preorder, p_end - (in_end - pos) + 1, p_end);
            return node;
    }
    
    int findRoot(int[] inorder, int in_start, int in_end, int key) {
        for(int i = in_start; i <= in_end; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章