forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 654.Maximum-Binary-Tree_v1.cpp
- Loading branch information
1 parent
9ec8fd0
commit 39745c6
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
Stack/654.Maximum-Binary-Tree/654.Maximum-Binary-Tree_v1.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |