|
4 | 4 | * int val; |
5 | 5 | * TreeNode left; |
6 | 6 | * TreeNode right; |
7 | | - * TreeNode(int x) { val = x; } |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
8 | 14 | * } |
9 | 15 | */ |
10 | 16 | class Solution { |
11 | 17 | public boolean isCousins(TreeNode root, int x, int y) { |
12 | | - if (root == null || x == y) { |
13 | | - return true; |
14 | | - } |
15 | | - ParentData p1 = new ParentData(); |
16 | | - ParentData p2 = new ParentData(); |
17 | | - helper(root, x, 0, null, p1); |
18 | | - helper(root, y, 0, null, p2); |
19 | | - return p1.depth == p2.depth && p1.parent != p2.parent; |
| 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]; |
20 | 23 | } |
21 | 24 |
|
22 | | - private void helper(TreeNode root, int x, int currDepth, TreeNode parent, ParentData p) { |
| 25 | + private void helper( |
| 26 | + TreeNode root, int num, int currDepth, TreeNode currParent, int[] depthAndParent |
| 27 | + ) { |
23 | 28 | if (root == null) { |
24 | 29 | return; |
25 | 30 | } |
26 | | - if (root.val == x) { |
27 | | - p.depth = currDepth; |
28 | | - p.parent = parent; |
| 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; |
29 | 35 | } |
30 | 36 | else { |
31 | | - helper(root.left, x, currDepth + 1, root, p); |
32 | | - helper(root.right, x, currDepth + 1, root, p); |
| 37 | + helper(root.left, num, currDepth + 1, root, depthAndParent); |
| 38 | + helper(root.right, num, currDepth + 1, root, depthAndParent); |
33 | 39 | } |
34 | 40 | } |
35 | 41 | } |
36 | | - |
37 | | -class ParentData { |
38 | | - int depth; |
39 | | - TreeNode parent; |
40 | | - |
41 | | - public ParentData() { |
42 | | - this.depth = 0; |
43 | | - this.parent = null; |
44 | | - } |
45 | | -} |
0 commit comments