leetbook_ioa/docs/LCR 174. 寻找二叉搜索树中的目标节点.md
本文解法基于性质:二叉搜索树的中序遍历为递增序列。根据此性质,易得二叉搜索树的 中序遍历倒序 为 递减序列 。
因此,我们可将求 “二叉搜索树第 $cnt$ 大的节点” 可转化为求 “此树的中序遍历倒序的第 $cnt$ 个节点”。
下图中的
k对应本题的cnt。
{:align=center width=450}
中序遍历 为 “左、根、右” 顺序,递归代码如下:
# 打印中序遍历
def dfs(root):
if not root: return
dfs(root.left) # 左
print(root.val) # 根
dfs(root.right) # 右
// 打印中序遍历
void dfs(TreeNode root) {
if(root == null) return;
dfs(root.left); // 左
System.out.println(root.val); // 根
dfs(root.right); // 右
}
void dfs(TreeNode* root) {
if(root == nullptr) return;
dfs(root->left);
cout << root->val;
dfs(root->right);
}
中序遍历的倒序 为 “右、根、左” 顺序,递归法代码如下:
# 打印中序遍历倒序
def dfs(root):
if not root: return
dfs(root.right) # 右
print(root.val) # 根
dfs(root.left) # 左
// 打印中序遍历倒序
void dfs(TreeNode root) {
if(root == null) return;
dfs(root.right); // 右
System.out.println(root.val); // 根
dfs(root.left); // 左
}
void dfs(TreeNode* root) {
if(root == nullptr) return;
dfs(root->right);
cout << root->val;
dfs(root->left);
}
为求第 $cnt$ 个节点,需要实现以下三项工作:
<,,,,,,>
题目指出:$1 \leq cnt \leq N$ (二叉搜索树节点个数);因此无需考虑 $cnt > N$ 的情况。 若考虑,可以在中序遍历完成后判断 $cnt > 0$ 是否成立,若成立则说明 $cnt > N$ 。
class Solution:
def findTargetNode(self, root: TreeNode, cnt: int) -> int:
def dfs(root):
if not root: return
dfs(root.right)
if self.cnt == 0: return
self.cnt -= 1
if self.cnt == 0: self.res = root.val
dfs(root.left)
self.cnt = cnt
dfs(root)
return self.res
class Solution {
int res, cnt;
public int findTargetNode(TreeNode root, int cnt) {
this.cnt = cnt;
dfs(root);
return res;
}
void dfs(TreeNode root) {
if(root == null) return;
dfs(root.right);
if(cnt == 0) return;
if(--cnt == 0) res = root.val;
dfs(root.left);
}
}
class Solution {
public:
int findTargetNode(TreeNode* root, int cnt) {
this->cnt = cnt;
dfs(root);
return res;
}
private:
int res, cnt;
void dfs(TreeNode* root) {
if(root == nullptr) return;
dfs(root->right);
if(cnt == 0) return;
if(--cnt == 0) res = root->val;
dfs(root->left);
}
};