Diameter of Binary Tree
LeetCode 543 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
diameter = max over nodes of (left height + right height).
मी Diameter of Binary Tree (LeetCode 543) असा सोडवला — Tree DP पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
The longest path bends at some node, going down its left side and its right side. At each node that length is left height + right height. Compute heights bottom-up and keep the best sum seen.
Approach
- 1
dfs returns the height of a subtree.
- 2
At each node, update the best with lh + rh.
- 3
Return 1 + max(lh, rh).
मी कसा सोडवला
Height DFS with global bestPythonO(n) time · O(h) space
class Solution:
def diameterOfBinaryTree(self, root):
self.maxDepth = float("-inf")
def dfs(node):
if node is None:
return 0
lh = dfs(node.left)
rh = dfs(node.right)
self.maxDepth = max(self.maxDepth, lh + rh)
return 1 + max(lh, rh)
dfs(root)
return self.maxDepthDiameter of Binary Tree — वारंवार विचारले जाणारे प्रश्न
Diameter of Binary Tree मागील intuition काय आहे?
The longest path bends at some node, going down its left side and its right side. At each node that length is left height + right height. Compute heights bottom-up and keep the best sum seen.
Diameter of Binary Tree (LeetCode 543) कसा सोडवावा?
1. dfs returns the height of a subtree. 2. At each node, update the best with lh + rh. 3. Return 1 + max(lh, rh).
Diameter of Binary Tree ची time आणि space complexity किती आहे?
Time: O(n). Space: O(h). (Accepted approach: Height DFS with global best.)
Diameter of Binary Tree मध्ये सामान्य चुका कोणत्या?
The path doesn't have to pass through the root.