|
15 | 15 | */
|
16 | 16 | class Solution {
|
17 | 17 | 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; |
21 | 21 | }
|
22 | 22 |
|
23 |
| - private NodeDetail getNodeDetail(TreeNode root, int n, TreeNode parent, int depth) { |
| 23 | + private ParentDepthPair getParentDepthPair(TreeNode root, int val, int currDepth) { |
24 | 24 | if (root == null) {
|
25 | 25 | return null;
|
26 | 26 | }
|
27 |
| - if (root.val == n) { |
28 |
| - return new NodeDetail(parent, depth); |
| 27 | + if (root.val == val) { |
| 28 | + return new ParentDepthPair(root, currDepth); |
29 | 29 | }
|
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); |
33 | 32 | }
|
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); |
35 | 35 | }
|
36 | 36 |
|
37 |
| - private class NodeDetail { |
| 37 | + private static class ParentDepthPair { |
38 | 38 | TreeNode parent;
|
39 | 39 | int depth;
|
40 |
| - |
41 |
| - public NodeDetail(TreeNode parent, int depth) { |
| 40 | + |
| 41 | + public ParentDepthPair(TreeNode parent, int depth) { |
42 | 42 | this.parent = parent;
|
43 | 43 | this.depth = depth;
|
44 | 44 | }
|
|
0 commit comments