-
Notifications
You must be signed in to change notification settings - Fork 1
/
Cousins in Binary Tree
62 lines (62 loc) · 1.51 KB
/
Cousins in Binary Tree
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* 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 {
private TreeNode par1 = null;
private TreeNode par2 = null;
public boolean isCousins(TreeNode root, int x, int y) {
int depth1 = findX(root, x, 0);
int depth2 = findY(root, y, 0);
if(depth1 != depth2){
return false;
}
else{
if(par1 == par2){
return false;
}
}
return true;
}
public int findX(TreeNode root, int val, int depth){
if(root == null){
return 0;
}
if(root.val == val){
return depth;
}
par1=root;
int height = findX(root.left,val,depth+1);
if(height!=0){
return height;
}
par1 = root;
return findX(root.right,val,depth+1);
}
public int findY(TreeNode root, int val, int depth){
if(root == null){
return 0;
}
if(root.val == val){
return depth;
}
par2=root;
int height = findY(root.left,val,depth+1);
if(height!=0){
return height;
}
par2 = root;
return findY(root.right,val,depth+1);
}
}