Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 114 · Construction / Serialization

Flatten Binary Tree to Linked List

LeetCode 114 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Recursion returns the tail of each flattened subtree.

मध्यमLinked ListStackTreeDepth-First SearchBinary Tree

मी Flatten Binary Tree to Linked List (LeetCode 114) असा सोडवला — Construction / Serialization पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Flatten each subtree recursively and get back its tail. Then splice: the left chain goes between the node and its right chain (left tail → old right), and the left pointer is cleared.

Approach

  1. 1

    None → None; a leaf is its own tail.

  2. 2

    Flatten left (tail LT) and right (tail RT).

  3. 3

    If there's a left chain: LT.right = root.right, root.right = root.left, root.left = None.

  4. 4

    Return RT if it exists, else LT.

मी कसा सोडवला

Return-the-tail recursionPythonO(n) time · O(h) space
# 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.
        """
        if root==None:
            return None
        if root.left==None and root.right==None:
            return root
        LT = self.flatten(root.left)
        RT = self.flatten(root.right)
        if LT!=None:
            LT.right = root.right #4->5
            root.right = root.left #need to remove the chain from left
            root.left = None #break the chain
        return LT if RT==None else RT
स्टेप-थ्रू लोड होत आहे…

Flatten Binary Tree to Linked List — वारंवार विचारले जाणारे प्रश्न

Flatten Binary Tree to Linked List मागील intuition काय आहे?

Flatten each subtree recursively and get back its tail. Then splice: the left chain goes between the node and its right chain (left tail → old right), and the left pointer is cleared.

Flatten Binary Tree to Linked List (LeetCode 114) कसा सोडवावा?

1. None → None; a leaf is its own tail. 2. Flatten left (tail LT) and right (tail RT). 3. If there's a left chain: LT.right = root.right, root.right = root.left, root.left = None. 4. Return RT if it exists, else LT.

Flatten Binary Tree to Linked List ची time आणि space complexity किती आहे?

Time: O(n). Space: O(h). (Accepted approach: Return-the-tail recursion.)

Flatten Binary Tree to Linked List मध्ये सामान्य चुका कोणत्या?

The function must still return a tail even though the API says None.