Tree
Traversals, BSTs, construction, path प्रॉब्लम और साफ़ recursive contracts के साथ tree DP।
DSAमध्यम24 घंटे8 पैटर्न · 40 प्रॉब्लम
0%
आपकी प्रगतिप्रॉब्लम और केस स्टडी के नाम, कोड और तकनीकी कीवर्ड अंग्रेज़ी में ही रखे गए हैं।
मूल विचार
Recursive contract तय करें: एक call क्या लौटाता है, और कौन-सा global जवाब अपडेट कर सकता है। Bottom-up aggregates के लिए post-order, context नीचे भेजने के लिए pre-order, levels के लिए BFS।
कब इस्तेमाल करें
- Hierarchical डेटा, BSTs, nodes के बीच paths
- Level-दर-level प्रश्न (BFS)
- Subtrees पर aggregates (height, diameter, sums)
टेम्पलेट
def diameter(root):
best = 0
def height(node):
nonlocal best
if not node:
return 0
l, r = height(node.left), height(node.right)
best = max(best, l + r)
return 1 + max(l, r)
height(root)
return bestComplexity
O(n) time, O(h) recursion stack (skewed trees में worst case O(n))।
आम गलतियाँ
- लौटाए गए मान को global जवाब से भ्रमित करना
- सिर्फ़ parent से तुलना करके BST validation (bounds चाहिए)
- Skewed इनपुट पर गहरी recursion की सीमा
इस कोर्स के पैटर्न
पहचान के संकेत
DFSBFSBSTConstructionTree DPPath/Distance