Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- # Definition for a binary tree node.
- # class TreeNode:
- # def __init__(self, val=0, left=None, right=None):
- # self.val = val
- # self.left = left
- # self.right = right
- class Solution:
- def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
- # Each element in my queue is a dict with attributes curr_node, parent_val, and depth
- queue = deque([{'curr_node': root, 'parent_val': None, 'depth': 0}])
- # Iterate BFS until we exhaust the tree
- while len(queue) > 0:
- # Access the current node
- curr_node_data = queue.popleft()
- curr_node = curr_node_data['curr_node']
- # If I find x or y:
- if curr_node.val == x or curr_node.val == y:
- # Search remainder of queue for the other value
- for node_data in queue:
- # If other value exists in queue:
- if (curr_node.val == x and node_data['curr_node'].val == y) or (curr_node.val == y and node_data['curr_node'].val == x):
- # Return True if x and y nodes have different parents and same level, False otherwise
- return curr_node_data['parent_val'] != node_data['parent_val'] and curr_node_data['depth'] == node_data['depth']
- # Return false if X or Y is found but the "opposite" is not found in the current queue
- return False
- # Continue iteration
- if curr_node.left:
- queue.append({'curr_node': curr_node.left, 'parent_val': curr_node.val, 'depth': curr_node_data['depth'] + 1})
- if curr_node.right:
- queue.append({'curr_node': curr_node.right, 'parent_val': curr_node.val, 'depth': curr_node_data['depth'] + 1})
- # If x and y do not exist in tree, return False
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement