Skip to content

Commit 2e2369a

Browse files
committed
binary_tree_preorder_traversal
1 parent 69919f1 commit 2e2369a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
127127
#### [141. Linked List Cycle](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle)
128128
#### [142. Linked List Cycle II](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle_II)
129129
#### [143. reorder list](https://github.com/hitzzc/go-leetcode/tree/master/reorder_list)
130+
#### [144. binary tree preorder traversal](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_preorder_traversal)
130131

131132

132133

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package binary_tree_preorder_traversal
2+
3+
type TreeNode struct {
4+
Val int
5+
Left *TreeNode
6+
Right *TreeNode
7+
}
8+
9+
func preorderTraversal(root *TreeNode) []int {
10+
rets := []int{}
11+
if root == nil {
12+
return rets
13+
}
14+
stack := []*TreeNode{}
15+
p := root
16+
for len(stack) != 0 || p != nil {
17+
for p != nil {
18+
rets = append(rets, p.Val)
19+
stack = append(stack, p)
20+
p = p.Left
21+
}
22+
if len(stack) != 0 {
23+
p = stack[len(stack)-1]
24+
stack = stack[:len(stack)-1]
25+
p = p.Right
26+
}
27+
}
28+
return rets
29+
}

0 commit comments

Comments
 (0)