Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created March 7, 2018 15:14
Show Gist options
  • Save s4553711/0d9db472b6c78bc381dbc58a9bb4916f to your computer and use it in GitHub Desktop.
Save s4553711/0d9db472b6c78bc381dbc58a9bb4916f to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(0, nums.size() - 1, nums);
}
TreeNode* build(int l, int r, vector<int>& nums) {
if (l > r) return NULL;
int idx = l;
for(int i = l + 1; i <= r; i++)
if (nums[i] > nums[idx]) idx = i;
TreeNode* root = new TreeNode(nums[idx]);
root->left = build(l, idx - 1, nums);
root->right = build(idx + 1, r, nums);
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment