forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CousinsInBinaryTree.java
40 lines (35 loc) · 1.12 KB
/
CousinsInBinaryTree.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
public class CousinsInBinaryTree {
public boolean isCousins(TreeNode root, int x, int y) {
NodeInfo X = getNodeInfo(root, x);
NodeInfo Y = getNodeInfo(root, y);
return X.depth == Y.depth && X.parent != Y.parent;
}
private NodeInfo getNodeInfo(TreeNode root, int val) {
if (root == null) return null;
if (root.val == val) return new NodeInfo(null, 0);
if (val(root.left) == val || val(root.right) == val) return new NodeInfo(root, 1);
NodeInfo left = getNodeInfo(root.left, val);
NodeInfo right = getNodeInfo(root.right, val);
if (left != null) {
left.depth++;
return left;
}
if (right != null) {
right.depth++;
return right;
}
return null;
}
private int val(TreeNode root) {
if (root == null) return 0;
return root.val;
}
private static class NodeInfo {
TreeNode parent;
int depth;
NodeInfo(final TreeNode parent, final int depth) {
this.parent = parent;
this.depth = depth;
}
}
}