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.