7.12 binary search tree

to do

7.12 binary search tree_第1张图片

1] Unique Binary Search Trees

    int numTrees(int n) {
        int dp[n+1]= {0};
        dp[0] = 1;
        
        for (int i=1; i

2] Unique Binary Search Trees II

注意loop内的顺序。。memory

    vector generateR(int l, int r) {
        if (l>r) return vector{nullptr};
        vector ret;
        
        for (int mid=l; mid ltrees = generateR(l, mid-1);
            vector rtrees = generateR(mid+1, r);
            for (auto l: ltrees) {
                for (auto r: rtrees) {
                    TreeNode* root = new TreeNode(mid);
                    root->left = l;
                    root->right = r;
                    ret.push_back(root);
                }
            }
        }
        return ret;
    }
    
    vector generateTrees(int n) {
        if (n<1) return vector{};
        return generateR(1, n);
    }

3] Validate Binary Search Tree

最基本的就是inorder了,但是这道正巧不允许重复。否则inorder无法detect duplicates' correctness(是吗??如果recurse时检查呢)

    void inorder(TreeNode* root, vector& record) {
        if (root->left) inorder(root->left, record);
        record.push_back(root->val);
        if (root->right) inorder(root->right, record);
    }
    
    bool isValidBST(TreeNode* root) {
        if (!root) return true;
        vector record;
        inorder(root, record);
        for (auto it=record.begin()+1; it

4] Convert Sorted Array to Binary Search Tree

careful not to be off by one

    TreeNode* sortedR(vector& nums, int l, int r) {
        if (l>r) return nullptr;
        
        int mid = (l+r)/2;
        TreeNode* midn = new TreeNode(nums[mid]);
        midn->left = sortedR(nums, l, mid-1);
        midn->right = sortedR(nums, mid+1, r);
        return midn;
    }
    
    TreeNode* sortedArrayToBST(vector& nums) {
        return sortedR(nums, 0, nums.size()-1);
    }

5] Convert Sorted List to Binary Search Tree

    TreeNode* sortedListToBST(ListNode* head) {
       if (!head) return nullptr;
       
       ListNode* prev = nullptr;
       ListNode* slow = head;
       for (ListNode *fast=head; fast->next&&fast->next->next; ) {
           prev = slow;
           slow = slow->next;
           fast = fast->next->next;
       }
       
       TreeNode* root = new TreeNode(slow->val);
       if (prev) {
           prev->next = nullptr;
           root->left = sortedListToBST(head);
       }
       if (slow->next) {
           root->right = sortedListToBST(slow->next);
       }
       
       return root;
    }

你可能感兴趣的:(7.12 binary search tree)