1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func preorderTraversal(root *TreeNode) []int { ans := []int{} node := root for node != nil { if node.Left != nil { postNode := node.Left for postNode.Right != nil && postNode.Right != node { postNode = postNode.Right } if postNode.Right == nil { ans = append(ans, node.Val) postNode.Right = node node = node.Left } else { node = node.Right postNode.Right = nil } } else { ans = append(ans, node.Val) node = node.Right } } return ans }
|