[LeetCode] 230. Kth Smallest Element in a BST

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 230. Kth Smallest Element in a BST相关的知识,希望对你有一定的参考价值。

二叉搜索树中第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

因为是BST所以大概率会碰到中序遍历inorder traversal,这一题也不例外。思路就是按照中序遍历的方法去遍历BST的节点,用count记录是否到K,输出第K个节点即可。我这里给的是递归的解法,比较方便。影子题671

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     private static int count;
 3     private static int res;
 4 
 5     public int kthSmallest(TreeNode root, int k) {
 6         count = k;
 7         helper(root);
 8         return res;
 9     }
10 
11     public void helper(TreeNode root) {
12         if (root == null) {
13             return;
14         }
15         helper(root.left);
16         count--;
17         if (count == 0) {
18             res = root.val;
19         }
20         helper(root.right);
21     }
22 }

 

javascript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @param {number} k
 4  * @return {number}
 5  */
 6 var kthSmallest = function (root, k) {
 7     let count = k;
 8     let res = 0;
 9 
10     let helper = function (root) {
11         if (root == null) {
12             return;
13         }
14         helper(root.left);
15         count--;
16         if (count == 0) {
17             res = root.val;
18         }
19         helper(root.right);
20     }
21     helper(root);
22     return res;
23 };

 

以上是关于[LeetCode] 230. Kth Smallest Element in a BST的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 230. Kth Smallest Element in a BST

Leetcode 230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

Leetcode 230: Kth Smallest Element in a BST

leetcode 230. Kth Smallest Element in a BST

[Leetcode] Binary search/tree-230. Kth Smallest Element in a BST