标签:esc arc 递归遍历 search ini tno modified ref ret
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.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ 1 4
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ 3 6
/ 2 4
/
1
Output: 3
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值相比较,如果大于k值,说明第k个值在左子树上,否则在当前节点或者右子树。递归遍历即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
int count = countNodes(root.left);
if (k <= count) {
return kthSmallest(root.left, k);
} else if (k > count + 1) {
return kthSmallest(root.right, k - 1 - count);
}
return root.val;
}
public int countNodes(TreeNode n) {
if (n == null) { return 0; }
return 1 + countNodes(n.left) + countNodes(n.right);
}
}
Leetcode 230. Kth Smallest Element in a BST
标签:esc arc 递归遍历 search ini tno modified ref ret
原文地址:https://www.cnblogs.com/xiagnming/p/9547526.html