[每日一题][找工作第40天][2025-11-1] Leetcode 114. 二叉树展开为链表(比官方优化一小步)

题目

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) 额外空间)展开这棵树吗?

我的代码(Python)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        t1 = root
        while t1 is not None:
            if t1.left is not None:
                if t1.right is not None:
                    t2 = t1.left
                    while t2.right is not None:
                        t2 = t2.right
                    t2.right = t1.right
                t1.right = t1.left
                t1.left = None
            t1 = t1.right
        return root

点评

O(1)的做法,要求在原结点上操作,思路是一个结点如果有左有右,则把右子结点接到左子树的最右结点上作为这个结点的右子结点。
和官方解法比起来,我多判断了一下右结点是否为空,因为如果右结点为空则不需要再找前置结点了,应该会提升效率。
实际也是100%的运行时间。


baddif@gmail.com

AI简历优化站

Nonpareil.me:优化简历,助力职场
开源代码

AI求职跟踪器(建设中)

开源代码

主站(建设中)

Nonpareil Me

相关平台

Github Issues / Notion / Blog

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部