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:


tree

Solution

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

根據(jù)inorder決定左右子樹的大小,根據(jù)preorder決定節(jié)點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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容