Skip to content

Commit a5b5c5a

Browse files
authored
Update Cousins in Binary Tree.java
1 parent 96a599f commit a5b5c5a

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

Easy/Cousins in Binary Tree.java

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,32 @@
1515
*/
1616
class Solution {
1717
public boolean isCousins(TreeNode root, int x, int y) {
18-
int[] depthAndParentX = {0, 0};
19-
int[] depthAndParentY = {0, 0};
20-
helper(root, x, 0, null, depthAndParentX);
21-
helper(root, y, 0, null, depthAndParentY);
22-
return depthAndParentX[0] == depthAndParentY[0] && depthAndParentX[1] != depthAndParentY[1];
18+
NodeDetail nodeDetailX = getNodeDetail(root, x, null, 0);
19+
NodeDetail nodeDetailY = getNodeDetail(root, y, null, 0);
20+
return nodeDetailX.depth == nodeDetailY.depth && nodeDetailX.parent != nodeDetailY.parent;
2321
}
2422

25-
private void helper(
26-
TreeNode root, int num, int currDepth, TreeNode currParent, int[] depthAndParent
27-
) {
23+
private NodeDetail getNodeDetail(TreeNode root, int n, TreeNode parent, int depth) {
2824
if (root == null) {
29-
return;
25+
return null;
3026
}
31-
if (root.val == num) {
32-
System.out.println(root.val + " " + num + " " + (currParent == null ? -1 : currParent.val));
33-
depthAndParent[0] = currDepth;
34-
depthAndParent[1] = currParent == null ? -1 : currParent.val;
27+
if (root.val == n) {
28+
return new NodeDetail(parent, depth);
3529
}
36-
else {
37-
helper(root.left, num, currDepth + 1, root, depthAndParent);
38-
helper(root.right, num, currDepth + 1, root, depthAndParent);
30+
NodeDetail left = getNodeDetail(root.left, n, root, depth + 1);
31+
if (left != null) {
32+
return left;
33+
}
34+
return getNodeDetail(root.right, n, root, depth + 1);
35+
}
36+
37+
private class NodeDetail {
38+
TreeNode parent;
39+
int depth;
40+
41+
public NodeDetail(TreeNode parent, int depth) {
42+
this.parent = parent;
43+
this.depth = depth;
3944
}
4045
}
4146
}

0 commit comments

Comments
 (0)