Skip to content

Instantly share code, notes, and snippets.

@rrain7
Last active August 8, 2021 13:03
Show Gist options
  • Select an option

  • Save rrain7/3c8c4bbcdc462838e3eae549594e2f23 to your computer and use it in GitHub Desktop.

Select an option

Save rrain7/3c8c4bbcdc462838e3eae549594e2f23 to your computer and use it in GitHub Desktop.
preOrder.go
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func preorderTraversal(root *TreeNode) []int {
result := []int{}
processNode := func(node *TreeNode) {
result = append(result, node.Val)
}
preorder(root, processNode)
}
func preorder(root *TreeNode, processNode func(*TreeNode)) {
if root != nil {
processNode(root)
preorder(root.Left, processNode)
preorder(root.Right, processNode)
}
}
// iterative
func preorderIterative(root *TreeNode) []int {
if root == nil {
return nil
}
stack := []*TreeNode{}
result := []int{}
current := root
for current != nil || len(stack) != 0 {
if current != nil {
result = append(result, current.Val)
current = current.Left
} else {
current = stack[len(stack)-1]
stack = stack[:len(stack)-1]
current = current.Right
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment