Binary Tree Level Order Traversal
LeetCode 102 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
BFS with a level marker.
ನಾನು Binary Tree Level Order Traversal (LeetCode 102) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — BFS / Level Order ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Breadth-first search with a queue visits nodes level by level. A marker ('\n') in the queue tells you where one level ends and the next begins.
Approach
- 1
Queue starts with root and a marker.
- 2
Pop: marker → re-append it and start a new level list.
- 3
Node → add its value and enqueue its children.
- 4
Stop when only the marker is left.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
BFS with markerPythonO(n) time · O(n) 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
queue=deque([root,"\n"])
res=[[]]
while len(queue)>1:
node= queue.popleft()
if node is None:
continue
if node is "\n":
queue.append(node)
res.append([])
continue
res[-1].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return resBinary Tree Level Order Traversal — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Binary Tree Level Order Traversal ಹಿಂದಿನ intuition ಏನು?
Breadth-first search with a queue visits nodes level by level. A marker ('\n') in the queue tells you where one level ends and the next begins.
Binary Tree Level Order Traversal (LeetCode 102) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Queue starts with root and a marker. 2. Pop: marker → re-append it and start a new level list. 3. Node → add its value and enqueue its children. 4. Stop when only the marker is left.
Binary Tree Level Order Traversal ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(n). (Accepted approach: BFS with marker.)
Binary Tree Level Order Traversal ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
`node is "\n"` relies on string interning; == is the safe comparison.