Leetcode Note: Go - N-Ary Tree Preorder Traversal

N-ary Tree Preorder Traversal - LeetCode
https://leetcode.com/problems/n-ary-tree-preorder-traversal/

  • Go 言語で取り組んだメモ

所感

  • linked list の node を int 配列にして return

回答

Python/Go O( n ) sol. based on recursive and iterative. [ w/ Explanation ] - LeetCode Discuss
https://leetcode.com/problems/n-ary-tree-preorder-traversal/discuss/475016/PythonGo-O(-n-)-sol.-based-on-recursive-and-iterative.-w-Explanation

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func preorder(root *Node) []int {
    path := []int{}
    dfs(root, &path)
    return path
}


func dfs(node *Node, path *[]int){
    
    // base case
    if node == nil {
        return
    }
    
    // general cases
    *path = append(*path, node.Val)
    
    for _, child := range node.Children{
        dfs(child, path)   
    }
    
    return
}
  • 再帰関数で node の value をチェックして return する int 配列を成形していく