C++ iterative solution with no additional space


  • 0
    R
    class Solution {
    public:
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            TreeNode* cur_max = new TreeNode(nums[0]);
            
            for (int i = 1; i < nums.size(); i++)
            {
                TreeNode* new_node = new TreeNode(nums[i]);
                
                if (nums[i] > cur_max->val)
                {
                    new_node->left = cur_max;
                    cur_max = new_node;
                }
                else
                {
                    TreeNode* insert = cur_max;
                    while (insert->right && insert->right->val > nums[i])
                        insert = insert->right;
                    new_node->left = insert->right;
                    insert->right = new_node;
                }
            }
            return cur_max;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.