|
8 | 8 | * }
|
9 | 9 | */
|
10 | 10 | class Solution {
|
11 |
| - public boolean isCousins(TreeNode root, int x, int y) { |
12 |
| - if (root == null) { |
13 |
| - return false; |
14 |
| - } |
15 |
| - |
16 |
| - DetailedNode nodeX = helper(root, null, x, 0); |
17 |
| - DetailedNode nodeY = helper(root, null, y, 0); |
18 |
| - |
19 |
| - if (nodeX == null || nodeY == null) { |
20 |
| - return false; |
21 |
| - } |
22 |
| - |
23 |
| - return nodeX.depth == nodeY.depth && nodeX.parent != nodeY.parent; |
| 11 | + public boolean isCousins(TreeNode root, int x, int y) { |
| 12 | + if (root == null || x == y) { |
| 13 | + return true; |
24 | 14 | }
|
25 |
| - |
26 |
| - private DetailedNode helper(TreeNode root, TreeNode parent, int num, int depth) { |
27 |
| - if (root == null) { |
28 |
| - return null; |
29 |
| - } |
30 |
| - |
31 |
| - if (root.val == num) { |
32 |
| - return new DetailedNode(root, parent, depth - 1); |
33 |
| - } |
34 |
| - |
35 |
| - DetailedNode left = helper(root.left, root, num, depth + 1); |
36 |
| - DetailedNode right = helper(root.right, root, num, depth + 1); |
37 |
| - |
38 |
| - if (left == null) { |
39 |
| - return right; |
40 |
| - } |
41 |
| - |
42 |
| - return left; |
| 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; |
| 20 | + } |
| 21 | + |
| 22 | + private void helper(TreeNode root, int x, int currDepth, TreeNode parent, ParentData p) { |
| 23 | + if (root == null) { |
| 24 | + return; |
43 | 25 | }
|
44 |
| - |
45 |
| - class DetailedNode { |
46 |
| - public TreeNode node; |
47 |
| - public TreeNode parent; |
48 |
| - public int depth; |
49 |
| - |
50 |
| - public DetailedNode(TreeNode node, TreeNode parent, int depth) { |
51 |
| - this.node = node; |
52 |
| - this.parent = parent; |
53 |
| - this.depth = depth; |
54 |
| - } |
| 26 | + if (root.val == x) { |
| 27 | + p.depth = currDepth; |
| 28 | + p.parent = parent; |
55 | 29 | }
|
| 30 | + else { |
| 31 | + helper(root.left, x, currDepth + 1, root, p); |
| 32 | + helper(root.right, x, currDepth + 1, root, p); |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +class ParentData { |
| 38 | + int depth; |
| 39 | + TreeNode parent; |
| 40 | + |
| 41 | + public ParentData() { |
| 42 | + this.depth = 0; |
| 43 | + this.parent = null; |
| 44 | + } |
56 | 45 | }
|
0 commit comments