144. 二叉樹的前序遍歷

gdut17_2發表於2024-06-07
/**
 * 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)
}

相關文章