-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathe993.py
32 lines (26 loc) · 989 Bytes
/
e993.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 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: Optional[TreeNode], x: int, y: int) -> bool:
# schema: (depth, parent)
ref = []
def dfs(curr: Optional[TreeNode], prev: Optional[TreeNode], depth: int = 0) -> None :
if not curr or len(ref) >= 2 :
return
if ref and depth > ref[0][0] :
return
if curr.val == x :
ref.append((depth, prev))
elif curr.val == y :
ref.append((depth, prev))
depth += 1
dfs(curr.left, curr, depth)
dfs(curr.right, curr, depth)
dfs(root, None)
if len(ref) < 2 :
return False
return ref[0][0] == ref[1][0] and ref[0][1] != ref[1][1]