【leetcode】【230】Kth Smallest Element in a BST

来源:互联网 发布:东海村核事故 知乎 编辑:程序博客网 时间:2024/05/22 12:07

一、问题描述

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.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

二、问题分析

结合BST的结构,可以采用中序遍历的方式,并且通过一个count值来统计遍历的个数,时间复杂度O(logn)。

三、Java AC代码

public int kthSmallest(TreeNode root, int k) {List<Integer> list = new ArrayList<Integer>();inOrderTraverse(root, list, k);return list.get(k-1);}public void inOrderTraverse(TreeNode root, List<Integer> list, int k){if (root == null || k<=0) {return ;}inOrderTraverse(root.left, list, k--);list.add(root.val);inOrderTraverse(root.right, list, k--);}


0 0