본문 바로가기

리트코드/midium

[리트코드] 230. Kth Smallest Element in a BST - js

반응형

1. 문제

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

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

2. 코드

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthSmallest = function(root, k) {
    let n = 0;
    let stack = [];
    let current = root;
    
    while (current || stack.length > 0) {
        while (current) {
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        n += 1;
        if (n === k) return current.val;
        current = current.right;
    }
};

트리 문제는 아직도 아예 감이 안온다... 연상이 잘 안된다.

반응형