【樹】B039_LC_先序遍歷構造二叉樹(分治思想)

一、Problem

Return the root node of a binary search tree that matches the given preorder traversal.

在這裏插入圖片描述

Constraints:

1 <= preorder.length <= 100
1 <= preorder[i] <= 10^8
The values of preorder are distinct.

二、Solution

方法一:遞歸

思路

根據 BST 性質可得,a[0] 就是 BST 的根,從左往右數第一個大於 a[0] 的值就是右子樹的開端,可基於這一點遞歸構造左右子樹

class Solution {
    TreeNode dfs(int l, int r, int[] a) {
        if (l > r)
            return null;
        TreeNode root = new TreeNode(a[l]);
        int rStart = l;
        while (rStart <= r && a[rStart] <= a[l])
            rStart++;
        root.left = dfs(l+1, rStart-1, a);
        root.right = dfs(rStart, r, a);
        return root;
    }
    public TreeNode bstFromPreorder(int[] preorder) {
        return dfs(0, preorder.length-1, preorder);
    }
}
複雜度分析
  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章