Created
February 26, 2020 17:49
-
-
Save alldroll/f47c0c42964005f6aabfd7c0e55f2bc5 to your computer and use it in GitHub Desktop.
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
| // 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