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.