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大的值 #77

Open
Liqiuyue9597 opened this issue Dec 10, 2020 · 0 comments
Open

二叉搜索树的第K大的值 #77

Liqiuyue9597 opened this issue Dec 10, 2020 · 0 comments

Comments

@Liqiuyue9597
Copy link
Owner

找到二叉搜索树的第K大的值,但是不能用另开存储空间将值全部存下来然后再找K大的值的解法。
剑指 Offer 54. 二叉搜索树的第k大节点.
这道题剑指offer是说中序遍历一遍就能得到从小到大的排序数组,但是面试官要求是不能用这种方式,当时是没想到用什么方法写。
下来查了一下,就是把中序遍历(左根右)倒序(右根左),就能得到从大到小的排序,这样直接找到最大。

function findKLargest(root, k) {
  let curr = root,
    stack = [];
  let count = 0;
  while (curr || stack.length > 0) {
    while (curr) {
      stack.push(curr);
      curr = curr.right;
    }
    curr = stack.pop();
    // res.push(curr.val);
    count++;
    if (count === k) {
      return curr.val;
    }
    curr = curr.left;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant