码迷,mamicode.com
首页 > 其他好文 > 详细

LC1008 Construct Binary Search Tree from Preorder Traversal

时间:2020-07-23 16:13:09      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:binary   from   nullptr   rsa   根据   nbsp   code   bre   break   

根据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

标签:binary   from   nullptr   rsa   根据   nbsp   code   bre   break   

原文地址:https://www.cnblogs.com/betaa/p/13365611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!