Binary Tree Postorder Traversal
LeetCode 145 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Left → right → node.
मी Binary Tree Postorder Traversal (LeetCode 145) असा सोडवला — Traversals (Recursive / Iterative) पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Post-order visits both children before the node itself — the order you'd use to delete a tree or combine child results.
Approach
- 1
dfs(None) returns.
- 2
dfs(left), dfs(right), then record node.val.
मी कसा सोडवला
Recursive DFSPythonO(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 postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def dfs(node):
if node==None:
return None
dfs(node.left)
dfs(node.right)
res.append(node.val)
dfs(root)
return resBinary Tree Postorder Traversal — वारंवार विचारले जाणारे प्रश्न
Binary Tree Postorder Traversal मागील intuition काय आहे?
Post-order visits both children before the node itself — the order you'd use to delete a tree or combine child results.
Binary Tree Postorder Traversal (LeetCode 145) कसा सोडवावा?
1. dfs(None) returns. 2. dfs(left), dfs(right), then record node.val.
Binary Tree Postorder Traversal ची time आणि space complexity किती आहे?
Time: O(n). Space: O(h). (Accepted approach: Recursive DFS.)
Binary Tree Postorder Traversal मध्ये सामान्य चुका कोणत्या?
Iterative post-order is the trickiest of the three — reversed (node, right, left) is a neat shortcut.