Solution for Golang


  • 0
    P

    Here is the iterative solution with a commented recursive solution:

    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    func preorderTraversal(root *TreeNode) []int {
        if root == nil {
            return []int{}
        }
        
        var ar []int
        var ns []*TreeNode = []*TreeNode{root}
        
        for len(ns) > 0 {
            var x *TreeNode = ns[len(ns)-1]
            ns = ns[:len(ns)-1]
            
            ar = append(ar, x.Val)
            
            if x.Right != nil {
                ns = append(ns, x.Right)
            }
            if x.Left != nil {
                ns = append(ns, x.Left)
            }
        }
        
        return ar
    }
    
    /** 
     * Recursive answer
     * func preorderTraversal(root *TreeNode) []int {
     *     var ar []int
     *   
     *     if (root == nil) {
     *         return ar
     *     }
     *  
     *     ar = append(ar, root.Val)
     *     ar = append(ar, preorderTraversal(root.Left)...)
     *     ar = append(ar, preorderTraversal(root.Right)...)
            
     *     return ar
     * }
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.