2019-11-02 12:07:41 +08:00
|
|
|
# 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);
|
|
|
|
}
|
|
|
|
```
|
2019-11-02 14:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|