-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtree.go
85 lines (74 loc) · 1.34 KB
/
tree.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package leetcode
import (
"container/list"
"log"
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func (n *TreeNode) FindVal(val int) *TreeNode {
if n == nil {
return nil
}
if n.Val == val {
return n
}
if l := n.Left.FindVal(val); l != nil {
return l
}
return n.Right.FindVal(val)
}
func (n *TreeNode) Equals(other *TreeNode) bool {
if n == nil || other == nil {
return n == other
}
if n.Val != other.Val {
return false
}
return n.Left.Equals(other.Left) && n.Right.Equals(other.Right)
}
func ParseTree(input string) *TreeNode {
// Trim start/end []
input = input[1 : len(input)-1]
// Split by comma
inputParts := strings.Split(input, ",")
n := len(inputParts)
if n == 0 || inputParts[0] == "" {
return nil
}
// Create one node per element in the array
nodes := make([]*TreeNode, n)
for i, part := range inputParts {
if part != "null" {
val, err := strconv.Atoi(part)
if err != nil {
log.Fatalln(err)
}
nodes[i] = &TreeNode{Val: val}
}
}
q := list.New()
q.PushBack(nodes[0])
i := 1
for q.Len() > 0 && i < n {
el := q.Remove(q.Front()).(*TreeNode)
if nodes[i] != nil {
el.Left = nodes[i]
q.PushBack(nodes[i])
}
i++
if i >= n {
break
}
if nodes[i] != nil {
el.Right = nodes[i]
q.PushBack(nodes[i])
}
i++
}
return nodes[0]
}