Leetcode刷题(第114题)——二叉树展开为链表

x33g5p2x  于2022-03-11 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(192)

一、题目

给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。

二、示例

输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
输入:root = []
输出:[]
输入:root = [0]
输出:[0]

三、解题思路
本题应当采用的方法是递归算法,将左右子树都转化为右链表的形式,然后将根节点的right执行左子树,然后再将右子树接在左子树的后面即可。
四、代码展示

/**
 * 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) {
    if (!root) return null

    let left = flatten(root.left)
    let right = flatten(root.right)
    let p = root
    root.left = null
    root.right = left
    while (root.right) {
        root = root.right
    }
    root.right = right
    return p
};

五、总结

相关文章

微信公众号

最新文章

更多