-
Notifications
You must be signed in to change notification settings - Fork 0
/
144.go
62 lines (53 loc) · 954 Bytes
/
144.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
package p144
/**
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func preorderTraversal(root *TreeNode) []int {
res := make([]int, 0)
visit := func(v int) {
res = append(res, v)
}
cur, prev := root, root
for cur != nil {
if cur.Left == nil {
visit(cur.Val)
cur = cur.Right
} else {
prev = cur.Left
for prev.Right != nil && prev.Right != cur {
prev = prev.Right
}
if prev.Right == nil {
visit(cur.Val)
prev.Right = cur
cur = cur.Left
} else {
cur = cur.Right
prev.Right = nil
}
}
}
return res
}