# 【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

07-07 9714

07-02 5913

05-24 1323

02-16 1757

04-29 321

08-03 801

08-02 2335

08-20 1805

08-02 1687

08-01 3438