↓Skip to main content
  1. LeetCode/

LeetCode 993: Cousins in Binary Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
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-09-26

  • Submissions: Wrong Answer ×4 → Runtime Error → Wrong Answer → Accepted ×3

Approach
#

Cousins need two conditions: the same depth and different parents (Tree Template 1). Carry the parent and depth through the DFS, record them for x and y, and check both conditions.

My Attempts
#

The early versions compared only depths, never parents. For [17, 3, 8], x = 3, y = 8 the two are siblings, so the answer is False; they returned True.

Solution
#

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        info = {}
        def dfs(node, parent, depth):
            if not node:
                return
            if node.val in (x, y):
                info[node.val] = (parent, depth)
            dfs(node.left, node, depth + 1)
            dfs(node.right, node, depth + 1)
        dfs(root, None, 0)
        (px, dx), (py, dy) = info[x], info[y]
        return dx == dy and px is not py

Complexity
#

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

Mistakes to Avoid
#

  • Siblings on the same level (same parent) are not cousins.

Interview Explanation
#

Cousins share a depth but not a parent, so a DFS records each one’s depth and parent, and I check both conditions. Time O(n).

Related

LeetCode 965: Univalued Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 note: every value must equal the root’s; compare values while recursing, not the booleans the recursion returns
LeetCode 637: Average of Levels in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 637 note: level-order traversal, dividing each level’s sum by its count
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 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
LeetCode 112: Path Sum
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 note: subtract each value from targetSum on the way down; it works if the remainder matches at a leaf