题目:给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
练习地址
https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
参考答案
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private int kth;
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null || k == 0) {
return null;
}
kth = k;
return KthNodeCore(pRoot);
}
private TreeNode KthNodeCore(TreeNode pRoot) {
TreeNode target = null;
if (pRoot.left != null) {
target = KthNodeCore(pRoot.left);
}
if (target == null && kth-- == 1) {
target = pRoot;
}
if (target == null && pRoot.right != null) {
target = KthNodeCore(pRoot.right);
}
return target;
}
}
复杂度分析
- 时间复杂度:O(n)。
- 空间复杂度:O(n)。