114. 二叉树展开为链表

46 阅读1分钟

给你二叉树的根结点 root ,请你将它展开为一个单链表:

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

示例 1:

image.png

输入: 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]

题解:

/**
 * 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 = []
    recursionFun(root, stack)

    for (let i = 1; i < stack.length; i++) {
        let cur = stack[i - 1], pre = stack[i];
        cur.left = null;
        cur.right = pre
    }
};
const recursionFun = (root, stack) => {
    if (root != null) {
        stack.push(root)
        recursionFun(root.left, stack)
        recursionFun(root.right, stack)
    }
}

// 方法二:迭代
var flatten = function (root) {
    const stack = [];
    let pre = null
    if (root) {
        stack.push(root);
        while (stack.length) {
            root = stack.pop();
            if (pre != null) {
                pre.left = null
                pre.right = root
            }
            if (root.right) stack.push(root.right)
            if (root.left) stack.push(root.left)
            pre = root // 缓存上一次节点
        }
    }
}
// 方法三:找前驱节点
var flatten = function (root) {
    let curr = root
    while (curr != null) {
        if (curr.left) {
            // next 和 pre指针指向当前节点
            let next = curr.left;
            let pre = next;
            // pre 获取左树上最右子节点
            while(pre.right){
                pre = pre.right;
            }
            // 最右子节点连接 当前节点的右节点 
            // 当前节点左节点指向null
            // 当前节点指向下一节点
            pre.right = curr.right
            curr.left = null
            curr.right = next
        }
        curr = curr.right
    }
}

来源:力扣(LeetCode)

链接:leetcode.cn/problems/fl…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。