Skip to content

Commit 39745c6

Browse files
authored
Create 654.Maximum-Binary-Tree_v1.cpp
1 parent 9ec8fd0 commit 39745c6

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
TreeNode* constructMaximumBinaryTree(vector<int>& nums)
13+
{
14+
return DFS(nums,0,nums.size()-1);
15+
}
16+
17+
TreeNode* DFS(vector<int>& nums, int start, int end)
18+
{
19+
int MAX=INT_MIN;
20+
int index=0;
21+
if (start>end) return NULL;
22+
23+
for (int i=start; i<=end; i++)
24+
{
25+
if (nums[i]>MAX)
26+
{
27+
MAX=nums[i];
28+
index=i;
29+
}
30+
}
31+
32+
TreeNode* root=new TreeNode(nums[index]);
33+
root->left=DFS(nums,start,index-1);
34+
root->right=DFS(nums,index+1,end);
35+
return root;
36+
}
37+
};

0 commit comments

Comments
 (0)