二叉树展开为链表(JS实现)

二叉树展开为链表(JS实现)

1 题目
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/
2 5
/ \
3 4 6
将其展开为:
1

2

3

4

5

6

2 思路
这道题我的思路比较直接,首先前序遍历树,然后用next指针链接每个节点,随后修改原来right指针,题解的方法比较巧妙,对树进行变形的后序遍历,遍历顺序是右子树->左子树->根节点
例如,我们依次遍历 6 5 4 3 2 1,然后每遍历一个节点就将当前节点的右指针更新为上一个节点,6 <- 5 <- 4 3 2 1

1
/ \
2 5
/ \ \
3 4 6

3代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var flatten = function(root) {
const stack = [];
let p = root;
let link = {};
let linkHead = link;

while (p || stack.length > 0) {
while (p) {
link.next = p;
link = link.next;
stack.push(p);
p = p.left;
}

p = stack.pop();
p = p.right;
}

link = linkHead.next;
while(link) {
root.right = link.next;
root.left = null;
root = root.right;
link = link.next;
}
};