Skip to content

114. 二叉树展开为链表 #44

Open
@webVueBlog

Description

@webVueBlog

114. 二叉树展开为链表

Description

Difficulty: 中等

Related Topics: , , 深度优先搜索, 链表, 二叉树

给你二叉树的根结点 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) 额外空间)展开这棵树吗?

Solution

Language: JavaScript

/**
 * 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.
 */
// 1. 先用两个变量把原先的左右子树保持起来
// 2. 将左子树作为右子树
// 3. 将原先的右子树接到当前右子树的末端
// 递归
var flatten = function(root) {
    // 递归终止
    if (root === null) return

    // 分别递归左右节点
    const left = root.left
    const right = root.right
    flatten(left)
    flatten(right)

    // 将树的right节点替换为left节点
    root.right = root.left
    root.left = null

    // 循环 找到最右的节点
    while (root.right) root = root.right
    // 最右的节点 指向right节点
    root.right = right
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions