Flatten Binary Tree to Linked List
LeetCode 114 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Recursion returns the tail of each flattened subtree.
ನಾನು 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
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.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
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 RTFlatten 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.