原题如下:leetcode.114 二叉树展开为链表
给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
方法1:
通过深度优先遍历,不断将二叉树拉平,
/**
* 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) {
let newNode = new TreeNode(0);
const result = newNode;
const list = [];
if (root) {
list.push(root);
}
while(list.length) {
const item = list.shift();
if (item.right) {
list.unshift(item.right);
}
if (item.left) {
list.unshift(item.left);
}
newNode.right = new TreeNode(item.val);
newNode = newNode.right;
}
if (result.right) {
root.right = result.right.right;
root.left = null;
}
};
方法2(递归):
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var flatten = function(root) {
if (!root) return;
flatten(root.left);
flatten(root.right);
// 拉平一个节点
const right = root.right;
root.right = root.left;
root.left = null;
let p = root;
while (p.right) {
p = p.right;
}
p.right = right;
};