[leetcode 230] Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

해결 과정

BST 이므로 inorder 순회하면서 정렬된 array를 만들고,

정렬된 array에서 k 번째 값을 반환한다.

코드

class Solution {
    var sortedArr: MutableList<Int> = mutableListOf()
    
    fun kthSmallest(root: TreeNode?, k: Int): Int {
        inorder(root)
        return sortedArr[k-1]
    }
    
    private fun inorder(root: TreeNode?) {
        if(null == root) return 
        
        inorder(root.left)
        sortedArr.add(root.`val`)
        inorder(root.right)
    }
}

배운 점

  • 문제를 풀면서 알게 된 방법들을 잘 습득해서 다른 문제에도 적용하자.

Leave a comment