【LeetCode】230.Kth Smallest Element in a BST(Medium)解题报告
题目地址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
题目描述:
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?
Solution:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
二叉搜索树是一个递增的序列
time : O(n)
space : O(n)
*/
class Solution {
private static int count = 0;
private static int res = 0;
public int kthSmallest(TreeNode root, int k) {
count = k;
helper(root);
return res;
}
public void helper(TreeNode root){
if(root==null) return;
helper(root.left);
count--;
if(count==0){
res = root.val;
}
helper(root.right);
}
}
Date:2018年3月11日