28 lines
655 B
Java
28 lines
655 B
Java
|
# 54. 二叉查找树的第 K 个结点
|
||
|
|
||
|
[NowCoder](https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||
|
|
||
|
## 解题思路
|
||
|
|
||
|
利用二叉查找树中序遍历有序的特点。
|
||
|
|
||
|
```java
|
||
|
private TreeNode ret;
|
||
|
private int cnt = 0;
|
||
|
|
||
|
public TreeNode KthNode(TreeNode pRoot, int k) {
|
||
|
inOrder(pRoot, k);
|
||
|
return ret;
|
||
|
}
|
||
|
|
||
|
private void inOrder(TreeNode root, int k) {
|
||
|
if (root == null || cnt >= k)
|
||
|
return;
|
||
|
inOrder(root.left, k);
|
||
|
cnt++;
|
||
|
if (cnt == k)
|
||
|
ret = root;
|
||
|
inOrder(root.right, k);
|
||
|
}
|
||
|
```
|