mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 19:13:42 +00:00
Update 36. 二叉搜索树与双向链表.md
补充利用中序遍历将二叉搜索树转换为双向链表的实现思路,以及修改指针不影响遍历的原理解释。
This commit is contained in:
@@ -10,6 +10,10 @@
|
||||
|
||||
## 解题思路
|
||||
|
||||
二叉搜索树的中序遍历是升序的,因此按中序遍历节点,用 pre 记录上一个访问的节点,访问 node 时把两者双向连起来:node.left = pre,pre.right = node。第一个访问的节点(最小值)就是链表头 head;遍历结束后 pre 指向最大的节点,再把 head 与 pre 首尾相连,得到循环双向链表。
|
||||
|
||||
修改指针不会影响遍历:改 node.left 时左子树已经遍历完,改 pre.right 时 pre 的右子树也已经遍历完或正在遍历(node 就在其中)。
|
||||
|
||||
```java
|
||||
private Node pre = null;
|
||||
private Node head = null;
|
||||
|
||||
Reference in New Issue
Block a user