Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

230. Kth Smallest Element in a BST #171

Open
Tcdian opened this issue May 21, 2020 · 1 comment
Open

230. Kth Smallest Element in a BST #171

Tcdian opened this issue May 21, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 21, 2020

230. Kth Smallest Element in a BST

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k最小的元素

你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

Example 1

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3
@Tcdian Tcdian added the Tree label May 21, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented May 21, 2020

Solution 1 ( 递归 )

  • JavaScript Solution
/**
 * 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 result;
    inorderTravel(root);
    return result;
    function inorderTravel(root) {
        if (result !== undefined || root === null) {
            return;
        }
        inorderTravel(root.left);
        if (--k === 0) {
            result = root.val;
            return;
        }
        inorderTravel(root.right);
    }
};

Solution 2 ( 迭代 )

  • JavaScript Solution
/**
 * 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 result;
    let patrol = root;
    const stack = [];
    while (stack.length !== 0 || patrol !== null) {
        while (patrol !== null) {
            stack.push(patrol);
            patrol = patrol.left;
        }
        patrol = stack.pop();
        if (--k === 0) {
            result = patrol.val;
            break;
        }
        patrol = patrol.right;
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant