Wednesday, September 27, 2017

654. Maximum Binary Tree

https://leetcode.com/problems/maximum-binary-tree/description/
Solution 1.
use a vector to keep part of tree nodes in decreasing order.
keep popping the vector until empty or a bigger number.
The bigger number (if exists) is current number's root, and the last popped number (if exist) is current number's right child and it is the parent of the number before last popped. 
push current number into the vector.
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        vector<TreeNode*> v;
        for(int n : nums) {
            TreeNode* node = new TreeNode(n);
            while(!v.empty() && v.back()->val<n) {
                node->left = v.back();
                v.pop_back();
            }
            if(!v.empty()) v.back()->right = node;
            v.push_back(node);
        }
        return v.front();
    }
Solution 2. Recursion
    TreeNode* construct(vector<int>& nums, int lo, int hi) {
        if(lo>hi) return nullptr;
        int mx = nums[lo], ix = lo;
        for(int i=lo+1; i<=hi;i++) if(nums[i]>mx) {
            mx = nums[i];
            ix = i;
        }
        TreeNode* node = new TreeNode(mx);
        node->left = construct(nums, lo, ix-1);
        node->right = construct(nums, ix+1, hi);
        return node;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return construct(nums, 0, nums.size()-1);
    }

No comments:

Post a Comment