【二叉树】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]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [0]
输出:[0]
 

提示:

树中结点数在范围 [0, 2000] 内
-100 <= Node.val <= 100
 

进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?

分析

方法一:后序遍历、递归

依据二叉树展开为链表的特点,使用后序遍历完成展开。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        def helper(root):
            if root is None: return
            helper(root.left) # 递归左子树
            helper(root.right) # 递归右子树
            # 后序遍历
            if root.left != None:
                pre = root.left # 令 pre 指向左子树
                while pre.right: 
                    pre = pre.right # 找到左子树中的最右节点
# 令左子树的最右节点的右子树,指向根节点的右子树 pre.right = root.right
# 令根节点的右子树指向根节点的左子树 root.right = root.left
root.left
= None # 置空根节点左子树 helper(root)

解法二: 非递归,不使用辅助空间及全局变量
前面的递归解法实际上也使用了额外的空间,因为递归需要占用额外空间。下面的解法无需申请栈,也不用全局变量,是真正的 In-Place 解法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        while (root != None):
            if root.left != None:
                most_right = root.left
                while most_right.right != None: most_right = most_right.right
                most_right.right = root.right
                root.right = root.left
                root.left = None
            root = root.right
        return
     

本人目前觉得第二种非递归方法更好理解,可以手动通过例子,逐行执行上述代码,即可对该思路理解更加清晰。

 

posted @ 2022-05-23 15:29  Ariel_一只猫的旅行  阅读(49)  评论(0编辑  收藏  举报