p230

LeetCode 230 Kth Smallest Element in a BST 题解

1.题目:

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?

题意:

输入一个二叉查找树和k,寻找这个数中第K小的数。

2.解题思路:

画张图跟如下代码走一遍应该就明白了。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {

int ans = 0;
TreeNode knode = root;

int c = count(knode.left);
if (c + 1 == k)
return knode.val;

if (c < k)
return kthSmallest(knode.right, k - 1 - c);// 往右的差值
if (c + 1 > k)
return kthSmallest(knode.left, k);

return ans;
}

public int count(TreeNode root) {

if (root == null)
return 0;

return 1 + count(root.left) + count(root.right);
}
}


4.一些总结: