From c8007a579450d9c11c7ebc24d2c54a32b948830d Mon Sep 17 00:00:00 2001 From: CyC2018 Date: Wed, 28 Oct 2026 13:45:06 +0800 Subject: [PATCH] =?UTF-8?q?Update=2054.=20=E4=BA=8C=E5=8F=89=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=E6=A0=91=E7=9A=84=E7=AC=AC=20K=20=E4=B8=AA=E7=BB=93?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 题目链接改为力扣中的对应题目,按该题求第 cnt 大的节点,改用右-根-左的逆中序遍历。 --- notes/54. 二叉查找树的第 K 个结点.md | 32 +++++++++++++++------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/notes/54. 二叉查找树的第 K 个结点.md b/notes/54. 二叉查找树的第 K 个结点.md index 0ace6217..b721f135 100644 --- a/notes/54. 二叉查找树的第 K 个结点.md +++ b/notes/54. 二叉查找树的第 K 个结点.md @@ -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); } ```