Skip to content

Commit fda1bd1

Browse files
committed
feat: medium: maximum-binary-tree.go
1 parent f9ca56d commit fda1bd1

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/medium/maximum-binary-tree.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package medium
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* type TreeNode struct {
6+
* Val int
7+
* Left *TreeNode
8+
* Right *TreeNode
9+
* }
10+
*/
11+
12+
// https://leetcode.com/problems/maximum-binary-tree
13+
func constructMaximumBinaryTree(nums []int) *TreeNode {
14+
if len(nums) == 0 {
15+
return nil
16+
}
17+
18+
maxIdx := 0
19+
for i := 1; i < len(nums); i++ {
20+
if nums[i] > nums[maxIdx] {
21+
maxIdx = i
22+
}
23+
}
24+
25+
return &TreeNode{
26+
Val: nums[maxIdx],
27+
Left: constructMaximumBinaryTree(nums[:maxIdx]),
28+
Right: constructMaximumBinaryTree(nums[maxIdx+1:]),
29+
}
30+
}

0 commit comments

Comments
 (0)