/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func preorderTraversal(root *TreeNode) []int {
return pre2(root)
// vals := []int{}
// pre1(root, &vals)
// return vals
}
func pre2(root *TreeNode) []int {
if root == nil {
return nil
}
stack := []*TreeNode{}
vals := []int{}
stack = append(stack, root)
for len(stack)>0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
vals = append(vals, node.Val)
if node.Right != nil {
stack = append(stack, node.Right)
}
if node.Left != nil {
stack = append(stack, node.Left)
}
}
return vals
}
func pre1(root *TreeNode, vals *[]int) {
if root == nil {
return
}
*vals = append(*vals, root.Val)
pre1(root.Left, vals)
pre1(root.Right, vals)
}
标签:node,144,TreeNode,int,前序,二叉树,vals,root,stack
From: https://www.cnblogs.com/gdut17code/p/18237951