mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 07:33:45 +00:00
Update 54. 二叉查找树的第 K 个结点.md
题目链接改为力扣中的对应题目,按该题求第 cnt 大的节点,改用右-根-左的逆中序遍历。
This commit is contained in:
+17
-15
@@ -1,31 +1,33 @@
|
||||
# 54. 二叉查找树的第 K 个结点
|
||||
|
||||
[NowCoder](https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff?tpId=13&tqId=2305268&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||||
[Leetcode](https://leetcode.cn/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
给定一棵二叉查找树,找出其中第 k 小的结点。
|
||||
给定一棵二叉搜索树,请找出其中第 cnt 大的节点的值。
|
||||
|
||||
## 解题思路
|
||||
|
||||
利用二叉查找树中序遍历有序的特点。
|
||||
二叉查找树的中序遍历(左-根-右)为升序序列,而逆中序遍历(右-根-左)即为降序序列。利用逆中序遍历访问到第 cnt 个节点即为目标值。
|
||||
|
||||
```java
|
||||
private TreeNode ret;
|
||||
private int cnt = 0;
|
||||
private int val;
|
||||
private int count = 0;
|
||||
|
||||
public TreeNode KthNode(TreeNode pRoot, int k) {
|
||||
inOrder(pRoot, k);
|
||||
return ret;
|
||||
public int findTargetNode(TreeNode root, int cnt) {
|
||||
inOrder(root, cnt);
|
||||
return val;
|
||||
}
|
||||
|
||||
private void inOrder(TreeNode root, int k) {
|
||||
if (root == null || cnt >= k)
|
||||
private void inOrder(TreeNode root, int cnt) {
|
||||
if (root == null || count >= cnt) {
|
||||
return;
|
||||
inOrder(root.left, k);
|
||||
cnt++;
|
||||
if (cnt == k)
|
||||
ret = root;
|
||||
inOrder(root.right, k);
|
||||
}
|
||||
inOrder(root.right, cnt);
|
||||
count++;
|
||||
if (count == cnt) {
|
||||
val = root.val;
|
||||
}
|
||||
inOrder(root.left, cnt);
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user