PS/LeetCode

LeetCode / Binary Search Tree / 230번 / Kth Smallest Element in a BST / JS

KimMinJun 2023. 4. 29. 18:00

< 문제 바로가기 >

 

Kth Smallest Element in a BST - LeetCode

Can you solve this real interview question? Kth Smallest Element in a BST - Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.   Example 1: [https://assets.leetco

leetcode.com

 

< 문제 간단설명 >

BST(Binary Search Tree) 에서 K번째로 작은 노드의 값을 반환하는 문제이다.

 

/**
 * 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 nodeList = [];

  // 전위 순회 (DFS)
  const traverse = (node) => {
    if (node === null) {
      return;
    }

    // 왼쪽 먼저 끝까지 순회하면서 nodeList에 넣고,
    traverse(node.left);
    nodeList.push(node.val);
    // 오른쪽 순회
    traverse(node.right);
  };

  traverse(root);

  // 전위 순회하면서 이미 정렬되어 있으므로 문제에 맞는 순서에 해당하는 값 반환
  let result = nodeList.at(k - 1);
  return result;
};