105. Construct Binary Tree from Preorder and Inorder Traversal

Description

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

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

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:


105. Construct Binary Tree from Preorder and Inorder Traversal_第1张图片
tree

Solution

DFS, time O(n), space O(1)

根据inorder决定左右子树的大小,根据preorder决定节点value。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeRecur(preorder, 0, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeRecur(int[] preorder, int ps
                                   , int[] inorder, int is, int ie) {
        if (is > ie) {
            return null;
        }
        
        TreeNode root = new TreeNode(preorder[ps]);
        int index = search(inorder, is, ie, root.val);
        root.left = buildTreeRecur(preorder, ps + 1
                                   , inorder, is, index - 1);
        root.right = buildTreeRecur(preorder, ps + index - is + 1
                                    , inorder, index + 1, ie);
        
        return root;
    }
    
    public int search(int[] nums, int start, int end, int val) {
        while (start <= end && nums[start] != val) {
            ++start;
        }
        
        return start;
    }
}

你可能感兴趣的:(105. Construct Binary Tree from Preorder and Inorder Traversal)