LC1008 Construct Binary Search Tree from Preorder Traversal

Posted betaa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC1008 Construct Binary Search Tree from Preorder Traversal相关的知识,希望对你有一定的参考价值。

根据BST的前序遍历重建BST

1. 平均O(NlogN) 最坏O(N^2)

class Solution {
public:
    TreeNode* dfs(int l, int r, vector<int>& p) {
        if (l > r) return nullptr;
        TreeNode* node = new TreeNode(p[l]);
        int i;
        for (i = l + 1; i <= r; ++i) {
            if (p[i] > p[l]) break;
        }
        node->left = dfs(l + 1, i - 1, p);
        node->right = dfs(i, r, p);
        return node;
    }
    TreeNode* bstFromPreorder(vector<int>& preorder) {
        return dfs(0, preorder.size() - 1, preorder);
    }
};

2. O(N)

class Solution {
public:
    int i = 0;
    TreeNode* bstFromPreorder(vector<int>& A, int bound = INT_MAX) {
        if (i == A.size() || A[i] > bound) return nullptr;
        TreeNode* root = new TreeNode(A[i++]);
        root->left = bstFromPreorder(A, root->val);
        root->right = bstFromPreorder(A, bound);
        return root;
    }
};

 

以上是关于LC1008 Construct Binary Search Tree from Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[LC] 105. Construct Binary Tree from Preorder and Inorder Traversal

[LeetCode] 1008. Construct Binary Search Tree from Preorder Traversal

[LC] 96. Unique Binary Search Trees

[LC] 951. Flip Equivalent Binary Trees

[LC] 951. Flip Equivalent Binary Trees

[LC] 95. Unique Binary Search Trees II