題目:給定一棵二叉搜索樹腮猖,請找出其中的第k小的結(jié)點坪创。例如莱预,(5,3危喉,7辜限,2,4岂座,6费什,8)中鸳址,按結(jié)點數(shù)值大小順序第三小結(jié)點的值為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)崩哩。