-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07. Cousins_in_a_Binary_Tree.java
46 lines (43 loc) · 1.12 KB
/
07. Cousins_in_a_Binary_Tree.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
HashMap<Integer, Pair> map = new HashMap<>();
public boolean isCousins(TreeNode root, int x, int y) {
traverse(root, 0, 0);
//Checking the given cousin condintion
if(map.get(x).height == map.get(y).height && map.get(x).parent!= map.get(y).parent){
return true;
}
return false;
}
//PreOrder Traversal Recursive method to store values
public void traverse(TreeNode root, int l, int p){
if(root == null)
return;
map.put(root.val, new Pair(l, p));
traverse(root.left, l+1, root.val);
traverse(root.right, l+1, root.val);
}
}
//A Pair Data class to store combined data about a node
class Pair {
int height;
int parent;
Pair(int h, int p){
this.height = h;
this.parent = p;
}
}