-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path993.cousins-in-binary-tree.java
69 lines (63 loc) · 1.81 KB
/
993.cousins-in-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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* 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;
* }
* }
*/
public class snode {
TreeNode node;
int d;
snode(TreeNode nodes, int depth){
this.node = nodes;
this.d = depth;
}
}
class Solution {
int dp1 = 0;
int dp2 = 0;
public boolean isCousins(TreeNode root, int x, int y) {
Stack<snode> stk = new Stack<snode>();
snode sn = new snode(root, 1);
stk.push(sn);
snode xx = null;
snode yy = null;
if(root!=null && root.val == x || root.val == y)
return false;
while(!stk.isEmpty()){
TreeNode temp = stk.peek().node;
int dep = stk.peek().d;
if(temp.val == x && xx == null){
snode a = stk.pop();
xx =stk.peek();
stk.push(a);
}
if(temp.val == y && yy == null){
snode b = stk.pop();
//if(!isEmptyStack)/
yy = stk.peek();
stk.push(b);
}
if(temp.left == null && temp.right == null)
stk.pop();
if(temp.left != null){
stk.push( new snode(temp.left, dep+1));
temp.left = null;
continue;
}
if(temp.right != null){
stk.push( new snode(temp.right, dep+1));
temp.right = null;
}
}
return xx.node.val != yy.node.val && xx.d == yy.d;
}
}