文章524
标签277
分类67

算法:二叉搜索树与双向链表


二叉搜索树与双向链表

二叉搜索树与双向链表

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。

要求不能创建任何新的结点,只能调整树中结点指针的指向。


分析

其实对于BST的中序遍历就是有序的了;

而针对双向链表的操作可以参考类似于链表翻转的过程: 从尾到头打印链表


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Stack;

public class Solution {
public TreeNode Convert(TreeNode root) {
if (root == null) return null;

Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root, pre = null;
boolean first = true;
// 中序遍历
while (!stack.isEmpty() || cur != null) {
// 左节点DFS
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
// 中序遍历
cur = stack.pop();
// 头结点处理
if (first) {
root = cur;
pre = root;
first = false;
// 中间节点处理
} else {
pre.right = cur;
cur.left = pre;
pre = cur;
}
cur = cur.right;
}
return root;
}
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/cn/1996/07/27/%E7%AE%97%E6%B3%95-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%8E%E5%8F%8C%E5%90%91%E9%93%BE%E8%A1%A8/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可