-
Notifications
You must be signed in to change notification settings - Fork 0
/
993_CousinsinBinaryTree_1.java
82 lines (78 loc) · 2.23 KB
/
993_CousinsinBinaryTree_1.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
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int xLevel = 0;
private int yLevel = 0;
private int xParent = 0;
private int yParent = 0;
public boolean isCousins(TreeNode root, int x, int y) {
loop(root, x, y, 0, 0);//先序遍历
return xLevel > 0 && xLevel == yLevel && xParent!= yParent;
}
private void loop(TreeNode root, int x, int y, int level, int parent){
if (root == null){
return;
}
if (x == root.val){
xLevel = level;
xParent = parent;
}else if (y == root.val){
yLevel = level;
yParent = parent;
}
loop(root.left, x, y, level+1, root.val);
loop(root.right, x, y, level+1, root.val);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//使用层序遍历
Map<Integer,Integer>height=new HashMap();//用来保持每个节点的高度
Map<Integer,Integer>parent=new HashMap(); //用来保存每个节点的父亲节点
public boolean isCousins(TreeNode root, int x, int y) {
if(root==null) return false;
Queue<TreeNode>queue=new LinkedList();
int h=0;
queue.offer(root);
height.put(root.val,0);
parent.put(root.val,null);
int size=1;
while(!queue.isEmpty()){
TreeNode node=queue.poll();
if(node.left!=null){
queue.offer(node.left);
height.put(node.left.val,h+1);
parent.put(node.left.val,node.val);
}
if(node.right!=null){
queue.offer(node.right);
height.put(node.right.val,h+1);
parent.put(node.right.val,node.val);
}
size--;
if(size==0){
h+=1;
size=queue.size();
}
}
if(height.get(x)==height.get(y)&&parent.get(x)!=parent.get(y)){
return true;
}
return false;
}
}