# 【LeetCode】Kth Smallest Element in a BST

## 问题描述

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

## 算法思想

BST中序遍历为排序序列，直接技术前k个访问的数即可得到第k个最小的元素

## 算法实现

public class Solution {
private int num = 0;
private int c = 0;
public void helper(TreeNode root, int k) {
if(root.left != null) {
helper(root.left, k);
}

c++;
if (k == c){
num = root.val;
return;
}

if (root.right != null) {
helper(root.right, k);
}
}
public int kthSmallest(TreeNode root, int k) {
helper(root,k);
return num;
}
}


T(n) = O(lgn)

## 演示结果

public static void main(String[] args) {
TreeNode root = new TreeNode(8);
TreeNode l1 = new TreeNode(1);
TreeNode l2 = new TreeNode(3);
TreeNode l3 = new TreeNode(6);
TreeNode l4 = new TreeNode(4);
TreeNode l5 = new TreeNode(7);
TreeNode l6 = new TreeNode(10);
TreeNode l7 = new TreeNode(14);
TreeNode l8 = new TreeNode(13);
root.left = l2;
root.right = l6;
l2.left = l1;
l2.right = l3;
l3.left = l4;
l3.right = l5;
l6.right = l7;
l7.left = l8;
Solution s = new Solution();
s.kthSmallest(root,3);
System.out.println(s.num);
}

4

• 本文已收录于以下专栏：

举报原因： 您举报文章：【LeetCode】Kth Smallest Element in a BST 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)