Tensorum
YouTubeশেখা শুরু করুন
LeetCode 543 · Tree DP

Diameter of Binary Tree

LeetCode 543 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

diameter = max over nodes of (left height + right height).

সহজTreeDepth-First SearchBinary TreeDP on Trees
LeetCode-এ খুলুন ↗

আমি 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. 1

    dfs returns the height of a subtree.

  2. 2

    At each node, update the best with lh + rh.

  3. 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.maxDepth
স্টেপ-থ্রু লোড হচ্ছে…

Diameter 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.