File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Stack/654.Maximum-Binary-Tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments