Last active
August 8, 2021 13:03
-
-
Save rrain7/3c8c4bbcdc462838e3eae549594e2f23 to your computer and use it in GitHub Desktop.
preOrder.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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