Skip to content

docs: add a description of the solution to lcof problem: No.54 #717

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

Merged
merged 1 commit into from
Feb 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion lcof/面试题54. 二叉搜索树的第k大节点/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,36 @@

## 解法

先遍历右子树,访问根节点,再遍历左子树。遍历到第 k 个结点时,存储结果。
朴素解法:

1. 中序遍历,并使用数组存储遍历结果。
2. 遍历结束,返回 `arr[arr.length - k]`。

*优化*:

其中,只关注**第 k 大节点的值**,可以选择倒序遍历,记录当前遍历节点的数量,当数量为 `k` 时,记录当前节点值做为返回值即可,而无需记录所有的遍历结果。

> 中序遍历的顺序是从小到大,倒序的中序遍历便是从大到小。

常规中序遍历:

```txt
IN-ORDER(R)
IN-ORDER(R.left)
print(R.val)
In-ORDER(R.right)
```

倒序中序遍历:

```txt
IN-ORDER-REVERSE(R)
In-ORDER-REVERSE(R.right)
print(R.val)
IN-ORDER-REVERSE(R.left)
```

若是抬杠说,可能每次 `k` 都是节点数量,那么倒序就毫无意义并且加长时间消耗。这些情况是无法假设的,如果 `k = 1`,那又该怎么说,选择倒序先得最大值,才是符合题意的精神。

<!-- tabs:start -->

Expand Down