forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCousins in Binary Tree.java
More file actions
46 lines (43 loc) · 1.21 KB
/
Cousins in Binary Tree.java
File metadata and controls
46 lines (43 loc) · 1.21 KB
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 {
public boolean isCousins(TreeNode root, int x, int y) {
NodeDetail nodeDetailX = getNodeDetail(root, x, null, 0);
NodeDetail nodeDetailY = getNodeDetail(root, y, null, 0);
return nodeDetailX.depth == nodeDetailY.depth && nodeDetailX.parent != nodeDetailY.parent;
}
private NodeDetail getNodeDetail(TreeNode root, int n, TreeNode parent, int depth) {
if (root == null) {
return null;
}
if (root.val == n) {
return new NodeDetail(parent, depth);
}
NodeDetail left = getNodeDetail(root.left, n, root, depth + 1);
if (left != null) {
return left;
}
return getNodeDetail(root.right, n, root, depth + 1);
}
private class NodeDetail {
TreeNode parent;
int depth;
public NodeDetail(TreeNode parent, int depth) {
this.parent = parent;
this.depth = depth;
}
}
}