Skip to content

Commit bf6e91e

Browse files
authored
docs: add a description of the solution to lcof problem: No.54 (#717)
面试题54. 二叉搜索树的第k大节点
1 parent cea509a commit bf6e91e

File tree

1 file changed

+30
-1
lines changed
  • lcof/面试题54. 二叉搜索树的第k大节点

1 file changed

+30
-1
lines changed

lcof/面试题54. 二叉搜索树的第k大节点/README.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,36 @@
4040

4141
## 解法
4242

43-
先遍历右子树,访问根节点,再遍历左子树。遍历到第 k 个结点时,存储结果。
43+
朴素解法:
44+
45+
1. 中序遍历,并使用数组存储遍历结果。
46+
2. 遍历结束,返回 `arr[arr.length - k]`
47+
48+
*优化*
49+
50+
其中,只关注**第 k 大节点的值**,可以选择倒序遍历,记录当前遍历节点的数量,当数量为 `k` 时,记录当前节点值做为返回值即可,而无需记录所有的遍历结果。
51+
52+
> 中序遍历的顺序是从小到大,倒序的中序遍历便是从大到小。
53+
54+
常规中序遍历:
55+
56+
```txt
57+
IN-ORDER(R)
58+
IN-ORDER(R.left)
59+
print(R.val)
60+
In-ORDER(R.right)
61+
```
62+
63+
倒序中序遍历:
64+
65+
```txt
66+
IN-ORDER-REVERSE(R)
67+
In-ORDER-REVERSE(R.right)
68+
print(R.val)
69+
IN-ORDER-REVERSE(R.left)
70+
```
71+
72+
若是抬杠说,可能每次 `k` 都是节点数量,那么倒序就毫无意义并且加长时间消耗。这些情况是无法假设的,如果 `k = 1`,那又该怎么说,选择倒序先得最大值,才是符合题意的精神。
4473

4574
<!-- tabs:start -->
4675

0 commit comments

Comments
 (0)