본문 바로가기
Computer/Algorithm

LeetCode - Binary Tree Postorder Traversal

by HanDongWook 2022. 9. 30.
반응형

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:

  • The number of the nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

풀이(Kotlin)

 - 재귀를통해 후위순회(left -> right -> root)를 풀이하였다.

/**
 * 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?): List<Int> {
        val list = ArrayList<Int>()
        postorder(root, list)
        return list
    }
    fun postorder(node: TreeNode?, list: MutableList<Int>) {
        if (node == null) return
        postorder(node.left, list)
        postorder(node.right, list)
        list.add(node.`val`)
    }
}
반응형

'Computer > Algorithm' 카테고리의 다른 글

LeetCode - Plus One  (0) 2022.10.01
LeetCode - Pascal's Triangle  (1) 2022.10.01
LeetCode - Binary Tree Preorder Traversal  (0) 2022.09.30
LeetCode - Binary Tree Inorder Traversal  (0) 2022.09.30
LeetCode - Longest Common Prefix  (0) 2022.09.30

댓글