您的位置:首页 > 其它

【LeetCode】230.Kth Smallest Element in a BST(Medium)解题报告

2018-03-11 10:11 543 查看
【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日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode tree