↓Skip to main content
  1. LeetCode/

LeetCode 543: Diameter of Binary Tree

·2 mins· ·
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Runtime Error ×5 → Wrong Answer ×3 → Runtime Error → Wrong Answer ×12 → Runtime Error ×2 → Accepted → Time Limit Exceeded → Accepted

Approach
#

The longest path through a node has left height + right height edges (Tree Templates 1 and 5). The longest one need not pass through the root, so check every node. A post-order recursion returns heights and updates the answer along the way.

My Attempts
#

This took 26 submissions in 2022, with three main errors:

  • Looking only at the root: maxDepth(root.left) + maxDepth(root.right) fails when the longest path skips the root. For [5, None, 8, 1, 7, 1, 2, 6] the longest path lies in the right subtree with length 4; it returned 3.
  • Returning one side’s height: max(left, right), e.g. [4, 4, 8] returned 1 instead of 2.
  • Counting nodes instead of edges: a single node [1] returned 1 instead of 0.

Solution
#

class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        best = 0
        def height(node):
            nonlocal best
            if not node:
                return 0
            l, r = height(node.left), height(node.right)
            best = max(best, l + r)                  # 經過這個節點的最長路徑
            return 1 + max(l, r)
        height(root)
        return best

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • The diameter counts edges, not nodes.
  • It may skip the root; update at every node.

Interview Explanation
#

The diameter may skip the root, so a post-order pass returns subtree heights and updates the answer with left plus right height at each node. One pass, time O(n).

Related

LeetCode 501: Find Mode in Binary Search Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 note: a BST’s in-order is sorted, so equal values are contiguous; count the current run during in-order, resetting the answer on a new maximum and appending on a tie
LeetCode 404: Sum of Left Leaves
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 note: tell each child during DFS whether it is a left child, adding only left children that are leaves
LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 145: Binary Tree Postorder Traversal
·2 mins
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 note: iterative post-order pushes a node back with a visited flag on its first pop, then the right and left children; record it on the second pop
LeetCode 110: Balanced Binary Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 note: every node’s subtree heights must differ by at most 1; return heights in post-order and propagate -1 once unbalanced
LeetCode 111: Minimum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 note: minimum depth must end at a leaf; with only one child, the empty side (depth 0) cannot count as the minimum