Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 26, 2020 17:49
Show Gist options
  • Select an option

  • Save alldroll/f47c0c42964005f6aabfd7c0e55f2bc5 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/f47c0c42964005f6aabfd7c0e55f2bc5 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/binary-tree-preorder-traversal
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func preorderTraversal(root *TreeNode) []int {
result := []int{}
stack := []*TreeNode{}
for root != nil {
if root.Right != nil {
stack = append(stack, root.Right)
}
if root.Left != nil {
stack = append(stack, root.Left)
}
result = append(result, root.Val)
if len(stack) > 0 {
root = stack[len(stack) - 1]
stack = stack[:len(stack) - 1]
} else {
root = nil
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment