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.