Problem
Analysis Process
Two kinds of solutions
One is Rescursive it is very easy
The other is Iterative
Start at the root node, each iteration pops the current top element and pushes its child onto the stack, pressing the right child first and then the left child
Code
Rescursive
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var res []int
func preorderTraversal(root *TreeNode) []int {
res = []int{}
dfs(root)
return res
}
func dfs(root *TreeNode) {
if root != nil {
res = append(res, root.Val)
dfs(root.Left)
dfs(root.Right)
}
}
Iterative
func preorderTraversal(root *TreeNode) []int {
var res []int
var stack []*TreeNode
for 0 < len(stack) || root != nil { //root != nil in order to determine the fist root must be put in the end
for root != nil {
res = append(res, root.Val) //preorder traversal to pop
stack = append(stack, root.Right) //ringt node push
root = root.Left //move to the left
}
index := len(stack) - 1 //top
root = stack[index] //pop
stack = stack[:index]
}
return res
}