Leetcode 1035 Solution

This article provides solution to leetcode question 1035 (cousins-in-binary-tree)

https://leetcode.com/problems/cousins-in-binary-tree

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
        if root is None:
            return []

        q = [(root, 0)]
        while q:
            s = len(q)

            node_vals = {}

            for i in range(s):
                node, seq = q.pop(0)

                node_vals[node.val] = seq

                if node.left:
                    q.append((node.left, 2 * seq + 1))
                if node.right:
                    q.append((node.right, 2 * seq + 2))

            if x in node_vals and y in node_vals:
                return int(abs(node_vals[x] - node_vals[y])) != 1
            elif x in node_vals or y in node_vals:
                return False