Skip to content

Commit ee96abf

Browse files
solves cousins in binary tre
1 parent f11123d commit ee96abf

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@
266266
| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array) | |
267267
| 985 | [Sum of Even Numbers after Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries) | |
268268
| 989 | [Add to Array Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer) | [![Java](assets/java.png)](src/AddToArrayFormOfInteger.java) |
269-
| 993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree) | |
269+
| 993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree) | [![Java](assets/java.png)](src/CousinsInBinaryTree.java) |
270270
| 997 | [Find the Town Judge](https://leetcode.com/problems/find-the-town-judge) | |
271271
| 999 | [Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook) | |
272272
| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters) | |

src/CousinsInBinaryTree.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class CousinsInBinaryTree {
2+
3+
public boolean isCousins(TreeNode root, int x, int y) {
4+
NodeInfo X = getNodeInfo(root, x);
5+
NodeInfo Y = getNodeInfo(root, y);
6+
return X.depth == Y.depth && X.parent != Y.parent;
7+
}
8+
9+
private NodeInfo getNodeInfo(TreeNode root, int val) {
10+
if (root == null) return null;
11+
if (root.val == val) return new NodeInfo(null, 0);
12+
if (val(root.left) == val || val(root.right) == val) return new NodeInfo(root, 1);
13+
NodeInfo left = getNodeInfo(root.left, val);
14+
NodeInfo right = getNodeInfo(root.right, val);
15+
if (left != null) {
16+
left.depth++;
17+
return left;
18+
}
19+
if (right != null) {
20+
right.depth++;
21+
return right;
22+
}
23+
return null;
24+
}
25+
26+
private int val(TreeNode root) {
27+
if (root == null) return 0;
28+
return root.val;
29+
}
30+
31+
private static class NodeInfo {
32+
TreeNode parent;
33+
int depth;
34+
35+
NodeInfo(final TreeNode parent, final int depth) {
36+
this.parent = parent;
37+
this.depth = depth;
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)