|
15 | 15 | */
|
16 | 16 | class Solution {
|
17 | 17 | 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; |
23 | 21 | }
|
24 | 22 |
|
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) { |
28 | 24 | if (root == null) {
|
29 |
| - return; |
| 25 | + return null; |
30 | 26 | }
|
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); |
35 | 29 | }
|
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; |
39 | 44 | }
|
40 | 45 | }
|
41 | 46 | }
|
0 commit comments