LeetCode in Kotlin

145. Binary Tree Postorder Traversal

Easy

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Example 1:

Input: root = [1,null,2,3]

Output: [3,2,1]

Example 2:

Input: root = []

Output: []

Example 3:

Input: root = [1]

Output: [1]

Constraints:

Follow up: Recursive solution is trivial, could you do it iteratively?

Solution

import com_github_leetcode.TreeNode

/*
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    fun postorderTraversal(root: TreeNode?): MutableList<Int> {
        if (root == null) {
            return ArrayList()
        }
        val res = postorderTraversal(root.left)
        res.addAll(postorderTraversal(root.right))
        res.add(root.`val`)
        return res
    }
}