Skip to content

Commit f311327

Browse files
author
Partho Biswas
committed
993. Cousins in Binary Tree
1 parent a72b046 commit f311327

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,7 @@ Check this [golden](https://tinyurl.com/ujopecz) post.
411411
|30| **[236. Lowest Common Ancestor of a Binary Tree](https://tinyurl.com/y54e6gco)**| [Python](https://tinyurl.com/wu6rdaw/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py)| **[Vid 1](https://tinyurl.com/udf9oa9)**, **[Vid 2](https://tinyurl.com/stknbyu)**, **[Algoexpert.io](https://tinyurl.com/wwz4m5t)**, **[Official](https://tinyurl.com/yx28t8ff)**, **[Art 1](https://tinyurl.com/v86wcky)**, **[Art 2](https://tinyurl.com/tu7jdzq)**, **[Art 3](https://tinyurl.com/tgvyy7p)** | Medium | TODO: Check Again. Very Important |
412412
|31| **[114. Flatten Binary Tree to Linked List](https://tinyurl.com/yyc6ol5w)**| [Python](https://tinyurl.com/wu6rdaw/114_Flatten_Binary_Tree_to_Linked_List.py)| [Art 1](https://tinyurl.com/v5s5axv) | Medium | Classic Prolem |
413413
|32| **[297. Serialize and Deserialize Binary Tree](https://tinyurl.com/ycfugzww)**| [Python](https://tinyurl.com/wu6rdaw/297_Serialize_and_Deserialize_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/297_Serialize_and_Deserialize_Binary_Tree.swift) | [Vid 1](https://tinyurl.com/yx4w25u4) | Hard | Classic Prolem |
414+
|33| **[993. Cousins in Binary Tree](https://tinyurl.com/ybtzjhnb)**| [Python](https://tinyurl.com/wu6rdaw/993_Cousins_in_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/993_Cousins_in_Binary_Tree.swift) | | Easy(Not so) | |
414415

415416
</p>
416417
</details>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution(object):
8+
def isCousins(self, root, x, y):
9+
"""
10+
:type root: TreeNode
11+
:type x: int
12+
:type y: int
13+
:rtype: bool
14+
"""
15+
xLevel, xParent = self.isCousinsHelperDFS(root, None, 0, x)
16+
yLevel, yParent = self.isCousinsHelperDFS(root, None, 0, y)
17+
18+
if xParent and yParent and (xParent != yParent) and (xLevel == yLevel):
19+
return True
20+
else:
21+
return False
22+
23+
def isCousinsHelperDFS(self, node, parent, currentLevel, x):
24+
if not node:
25+
return (0, None)
26+
if node.val == x:
27+
return (currentLevel, parent)
28+
29+
leftLevel, leftParent = self.isCousinsHelperDFS(node.left, node, currentLevel + 1, x)
30+
rightLevel, rightParent = self.isCousinsHelperDFS(node.right, node, currentLevel + 1, x)
31+
if leftParent:
32+
return (leftLevel, leftParent)
33+
else:
34+
return (rightLevel, rightParent)
35+
36+

0 commit comments

Comments
 (0)