-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmaximum-width-of-binary-tree.go
More file actions
59 lines (47 loc) · 961 Bytes
/
maximum-width-of-binary-tree.go
File metadata and controls
59 lines (47 loc) · 961 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func widthOfBinaryTree(root *TreeNode) int {
if root == nil {
return 0
}
minOnLevel := map[int]int{}
result := 1
updateMin := func(level int, pos int) {
_, ok := minOnLevel[level]
if !ok {
minOnLevel[level] = pos
}
if pos < minOnLevel[level] {
minOnLevel[level] = pos
}
diff := pos - minOnLevel[level] + 1
if diff > result {
result = diff
}
}
var dfs func(node *TreeNode, level int, pos int)
dfs = func(node *TreeNode, level int, pos int) {
if node.Left != nil {
newPos := pos*2 + 1
updateMin(level, newPos)
dfs(node.Left, level+1, newPos)
}
if node.Right != nil {
newPos := pos*2 + 2
updateMin(level, newPos)
dfs(node.Right, level+1, newPos)
}
}
dfs(root, 0, 0)
return result
}
func main() {
root := &TreeNode{1, nil, nil}
node := &TreeNode{2, nil, nil}
root.Left = node
widthOfBinaryTree(root)
}