解题思路
- 因为是二叉搜索树,采用中序遍历刚好满足顺序条件
- 中序遍历时,先判断pre是否有值,若无值,则表示当前是表头节点,赋值为head;若有值,更新指针,双向连接(pre.right = cur;cur.left = pre;)
- 更新pre,将当前节点作为一下个节点的上一个节点
- 最后要将头部节点和尾部节点相连
const treeToDoublyList = root => {
let pre, head;
const dfs = cur => {
if (!cur) return;
dfs(cur.left);
if (!pre) {
// pre为空 首次调用到左叶子节点 以它为头
head = cur;
} else {
// pre有值,pre和cur相互所指
pre.right = cur;
cur.left = pre;
}
// 当前的pre已完成使命了,指针右移动,吧cur作为下一次的pre
pre = cur;
dfs(cur.right);
};
if (!root) return;
dfs(root);
// 首尾指针相互指
head.left = pre;
pre.right = head;
return head;
};
添加下面代码,打断点调试过程
var obj = {
val: 4,
left: {
val: 2,
left: {
val: 1,
left: null,
right: null,
},
right: {
val: 3,
left: null,
right: 3,
},
},
right: {
val: 5,
left: null,
right: null,
},
};
treeToDoublyList(obj);
调试例子的结构如图所示