This repository was archived by the owner on Sep 20, 2023. It is now read-only.
File tree 3 files changed +34
-4
lines changed
Algorithms/0654.maximum-binary-tree
3 files changed +34
-4
lines changed Original file line number Diff line number Diff line change @@ -19,8 +19,8 @@ Output: return the tree root node representing the following tree:
19
19
6
20
20
/ \
21
21
3 5
22
- \ /
23
- 2 0
22
+ \ /
23
+ 2 0
24
24
\
25
25
1
26
26
```
Original file line number Diff line number Diff line change @@ -7,6 +7,31 @@ import (
7
7
type TreeNode = kit.TreeNode
8
8
9
9
func constructMaximumBinaryTree (nums []int ) * TreeNode {
10
+ if len (nums ) == 0 {
11
+ return nil
12
+ }
10
13
11
- return nil
14
+ if len (nums ) == 1 {
15
+ return & TreeNode {Val : nums [0 ]}
16
+ }
17
+
18
+ v , i := getMax (nums )
19
+
20
+ return & TreeNode {
21
+ Val : v ,
22
+ Left : constructMaximumBinaryTree (nums [:i ]),
23
+ Right : constructMaximumBinaryTree (nums [i + 1 :]),
24
+ }
25
+ }
26
+
27
+ func getMax (nums []int ) (val , index int ) {
28
+ val = nums [0 ]
29
+ index = 0
30
+ for i := 1 ; i < len (nums ); i ++ {
31
+ if val < nums [i ] {
32
+ val = nums [i ]
33
+ index = i
34
+ }
35
+ }
36
+ return val , index
12
37
}
Original file line number Diff line number Diff line change @@ -15,7 +15,12 @@ var tcs = []struct {
15
15
post []int
16
16
}{
17
17
18
- // 可以有多个 testcase
18
+ {
19
+ []int {3 , 2 , 1 , 6 , 0 , 5 },
20
+ []int {1 , 2 , 3 , 0 , 5 , 6 },
21
+ },
22
+
23
+ // 可以有多个 testcase
19
24
}
20
25
21
26
func Test_fn (t * testing.T ) {
You can’t perform that action at this time.
0 commit comments