Skip to content

Commit

Permalink
Create 654.Maximum-Binary-Tree_v1.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jan 13, 2022
1 parent 9ec8fd0 commit 39745c6
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* 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 DFS(nums,0,nums.size()-1);
}

TreeNode* DFS(vector<int>& nums, int start, int end)
{
int MAX=INT_MIN;
int index=0;
if (start>end) return NULL;

for (int i=start; i<=end; i++)
{
if (nums[i]>MAX)
{
MAX=nums[i];
index=i;
}
}

TreeNode* root=new TreeNode(nums[index]);
root->left=DFS(nums,start,index-1);
root->right=DFS(nums,index+1,end);
return root;
}
};

0 comments on commit 39745c6

Please sign in to comment.