Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉搜索树的第 k 大的节点 | HZFE - 剑指前端 Offer #66

Open
utterances-bot opened this issue Mar 2, 2022 · 1 comment
Assignees

Comments

@utterances-bot
Copy link

二叉搜索树的第 k 大的节点 | HZFE - 剑指前端 Offer

题目描述

https://febook.hzfe.org/awesome-interview/book3/algorithm-binary-tree-k

Copy link

WebChn commented Mar 2, 2022

解法1 加一个return 是不是可以减少一些执行
const kthLargest = (root, k) => {
let res = null; // 初始化返回值
// 因为需要倒序第 k 个,所以处理是右节点,根节点,然后左节点
const dfs = (root) => {
if (!root) return; // 如果当前节点为 null,本轮处理结束
dfs(root.right); // 开始处理右节点
if (k === 0) return; // k 值 为 0,代表已经处理的节点超过目标节点,本轮处理结束
if (--k === 0) {
// 当 k 值 减 1 为 0,表示已经到了我们想要的 k 大 节点,保存当前值
res = root.val;
return // 这里已经拿到第 k 大的值了 后续的dfs(root.left); 不用再执行了
}
dfs(root.left); // 处理左节点
};
dfs(root); // 从初始化节点开始处理
return res;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants