Leetcode Note: Go - Binary Tree Postorder Traversal

Binary Tree Postorder Traversal - LeetCode
https://leetcode.com/problems/binary-tree-postorder-traversal/

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

所感

  • Pre Order のコードをカスタマイズすれば実現できそう

回答

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func postorderTraversal(root *TreeNode) []int {
    traversal := []int{}

    var postorder func(*TreeNode)
    
    postorder = func(root *TreeNode) {
        if root == nil {
            return
        }
        
        postorder(root.Left)
        postorder(root.Right)
        traversal = append(traversal, root.Val)
    }
    
    postorder(root)

    return traversal
}
  • 目論見通り