题目描述
给你二叉树的根结点 root ,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
- 展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [0]
输出:[0]
提示:
- 树中结点数在范围 [0, 2000] 内
- -100 <= Node.val <= 100
进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?
个人解法
Javascript
使用数组保存先序遍历的节点
/*
* @lc app=leetcode.cn id=114 lang=javascript
*
* [114] 二叉树展开为链表
*/
// @lc code=start
/**
* 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 result = [];
if (root === null) return null;
var fun = function (root) {
if (root === null) return;
result.push(root);
fun(root.left);
fun(root.right);
}
fun(root);
const len = result.length;
for (let i = 1; i < len; i++) {
let temp = result[i - 1];
temp.left = null;
temp.right = result[i];
}
};
// @lc code=end
Java
其他解法
Java
Javascript
题解链接
空间复杂度为1的算法
var flatten = function(root) {
let curr = root;
while (curr !== null) {
if (curr.left !== null) {
const next = curr.left;
let predecessor = next;
while (predecessor.right !== null) {
predecessor = predecessor.right;
}
predecessor.right = curr.right;
curr.left = null;
curr.right = next;
}
curr = curr.right;
}
};