Skip to content

Commit c625fb1

Browse files
author
hero
committed
654. 最大二叉树
1 parent 046d152 commit c625fb1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leet_code
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func constructMaximumBinaryTree(nums []int) *TreeNode {
8+
return maxTreeNode(nums, 0, len(nums)-1)
9+
}
10+
11+
func maxTreeNode(num []int, i, j int) *TreeNode {
12+
if i > j {
13+
return nil
14+
}
15+
modI := findMaxIndex(num, i, j)
16+
root := new(TreeNode)
17+
root.Val = num[modI]
18+
root.Left = maxTreeNode(num, i, modI-1)
19+
root.Right = maxTreeNode(num, modI+1, j)
20+
return root
21+
}
22+
23+
func findMaxIndex(num []int, i, j int) int {
24+
var (
25+
index = -1
26+
indexNum = -1
27+
)
28+
for k := i; k <= j; k++ {
29+
if indexNum < num[k] {
30+
indexNum = num[k]
31+
index = k
32+
}
33+
}
34+
return index
35+
}
36+
37+
func Test_constructMaximumBinaryTree(t *testing.T) {
38+
num := []int{3, 2, 1, 6, 0, 5}
39+
constructMaximumBinaryTree(num)
40+
}

0 commit comments

Comments
 (0)