Skip to content

Commit 000bad1

Browse files
authored
Update Cousins in Binary Tree.java
1 parent 64a9ece commit 000bad1

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

Easy/Cousins in Binary Tree.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,30 +15,30 @@
1515
*/
1616
class Solution {
1717
public boolean isCousins(TreeNode root, int x, int y) {
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;
18+
ParentDepthPair xPair = getParentDepthPair(root, x, 0);
19+
ParentDepthPair yPair = getParentDepthPair(root, y, 0);
20+
return xPair.parent != yPair.parent && xPair.depth == yPair.depth;
2121
}
2222

23-
private NodeDetail getNodeDetail(TreeNode root, int n, TreeNode parent, int depth) {
23+
private ParentDepthPair getParentDepthPair(TreeNode root, int val, int currDepth) {
2424
if (root == null) {
2525
return null;
2626
}
27-
if (root.val == n) {
28-
return new NodeDetail(parent, depth);
27+
if (root.val == val) {
28+
return new ParentDepthPair(root, currDepth);
2929
}
30-
NodeDetail left = getNodeDetail(root.left, n, root, depth + 1);
31-
if (left != null) {
32-
return left;
30+
if ((root.left != null && root.left.val == val) || (root.right != null && root.right.val == val)) {
31+
return new ParentDepthPair(root, currDepth);
3332
}
34-
return getNodeDetail(root.right, n, root, depth + 1);
33+
ParentDepthPair leftPair = getParentDepthPair(root.left, val, currDepth + 1);
34+
return leftPair != null ? leftPair : getParentDepthPair(root.right, val, currDepth + 1);
3535
}
3636

37-
private class NodeDetail {
37+
private static class ParentDepthPair {
3838
TreeNode parent;
3939
int depth;
40-
41-
public NodeDetail(TreeNode parent, int depth) {
40+
41+
public ParentDepthPair(TreeNode parent, int depth) {
4242
this.parent = parent;
4343
this.depth = depth;
4444
}

0 commit comments

Comments
 (0)