75
75
class Solution :
76
76
def isCousins (self , root : Optional[TreeNode], x : int , y : int ) -> bool :
77
77
q = deque([(root, None )])
78
- d = 0
78
+ depth = 0
79
79
p1 = p2 = None
80
- d1 = d2 = 0
80
+ d1 = d2 = None
81
81
while q:
82
82
for _ in range (len (q)):
83
- node, fa = q.popleft()
83
+ node, parent = q.popleft()
84
84
if node.val == x:
85
- p1, d1 = fa, d
86
- if node.val == y:
87
- p2, d2 = fa, d
85
+ p1, d1 = parent, depth
86
+ elif node.val == y:
87
+ p2, d2 = parent, depth
88
88
if node.left:
89
89
q.append((node.left, node))
90
90
if node.right:
91
91
q.append((node.right, node))
92
- d += 1
92
+ depth += 1
93
93
return p1 != p2 and d1 == d2
94
94
```
95
95
@@ -111,22 +111,20 @@ class Solution:
111
111
*/
112
112
class Solution {
113
113
public boolean isCousins (TreeNode root , int x , int y ) {
114
- TreeNode p1 = null , p2 = null ;
115
- int d1 = 0 , d2 = 0 ;
116
114
Deque<TreeNode []> q = new ArrayDeque<> ();
117
115
q. offer(new TreeNode [] {root, null });
118
- int d = 0 ;
119
- while (! q. isEmpty()) {
116
+ int d1 = 0 , d2 = 0 ;
117
+ TreeNode p1 = null , p2 = null ;
118
+ for (int depth = 0 ; ! q. isEmpty(); ++ depth) {
120
119
for (int n = q. size(); n > 0 ; -- n) {
121
- var p = q. poll();
122
- TreeNode node = p [0 ], fa = p [1 ];
120
+ TreeNode [] t = q. poll();
121
+ TreeNode node = t [0 ], parent = t [1 ];
123
122
if (node. val == x) {
124
- p1 = fa;
125
- d1 = d;
126
- }
127
- if (node. val == y) {
128
- p2 = fa;
129
- d2 = d;
123
+ d1 = depth;
124
+ p1 = parent;
125
+ } else if (node. val == y) {
126
+ d2 = depth;
127
+ p2 = parent;
130
128
}
131
129
if (node. left != null ) {
132
130
q. offer(new TreeNode [] {node. left, node});
@@ -135,7 +133,6 @@ class Solution {
135
133
q. offer(new TreeNode [] {node. right, node});
136
134
}
137
135
}
138
- ++ d;
139
136
}
140
137
return p1 != p2 && d1 == d2;
141
138
}
@@ -157,34 +154,30 @@ class Solution {
157
154
class Solution {
158
155
public:
159
156
bool isCousins(TreeNode* root, int x, int y) {
160
- TreeNode* p1 = nullptr;
161
- TreeNode* p2 = nullptr;
162
- int d1 = 0, d2 = 0;
163
157
queue<pair<TreeNode* , TreeNode* >> q;
164
- q.emplace(root, nullptr);
165
- int d = 0;
166
- while (!q.empty()) {
158
+ q.push({root, nullptr});
159
+ int d1 = 0, d2 = 0;
160
+ TreeNode * p1 = nullptr, * p2 = nullptr;
161
+ for (int depth = 0; q.size(); ++depth) {
167
162
for (int n = q.size(); n; --n) {
168
- auto [ node, fa ] = q.front();
163
+ auto [ node, parent ] = q.front();
169
164
q.pop();
170
165
if (node->val == x) {
171
- p1 = fa;
172
- d1 = d;
173
- }
174
- if (node->val == y) {
175
- p2 = fa;
176
- d2 = d;
166
+ d1 = depth;
167
+ p1 = parent;
168
+ } else if (node->val == y) {
169
+ d2 = depth;
170
+ p2 = parent;
177
171
}
178
172
if (node->left) {
179
- q.emplace( node->left, node);
173
+ q.push({ node->left, node} );
180
174
}
181
175
if (node->right) {
182
- q.emplace( node->right, node);
176
+ q.push({ node->right, node} );
183
177
}
184
178
}
185
- ++d;
186
179
}
187
- return p1 != p2 && d1 == d2 ;
180
+ return d1 == d2 && p1 != p2 ;
188
181
}
189
182
};
190
183
```
@@ -199,20 +192,18 @@ public:
199
192
* }
200
193
*/
201
194
func isCousins(root *TreeNode, x int, y int) bool {
202
- type pair struct{ node, fa *TreeNode }
203
- q := []pair{pair{root, nil}}
195
+ type pair struct{ node, parent *TreeNode }
196
+ var d1, d2 int
204
197
var p1, p2 *TreeNode
205
- var d, d1, d2 int
206
- for len(q) > 0 {
198
+ q := []pair{{root, nil}}
199
+ for depth := 0; len(q) > 0; depth++ {
207
200
for n := len(q); n > 0; n-- {
208
- p := q[0]
201
+ node, parent := q[0].node, q[0].parent
209
202
q = q[1:]
210
- node, fa := p.node, p.fa
211
203
if node.Val == x {
212
- p1, d1 = fa, d
213
- }
214
- if node.Val == y {
215
- p2, d2 = fa, d
204
+ d1, p1 = depth, parent
205
+ } else if node.Val == y {
206
+ d2, p2 = depth, parent
216
207
}
217
208
if node.Left != nil {
218
209
q = append(q, pair{node.Left, node})
@@ -221,19 +212,58 @@ func isCousins(root *TreeNode, x int, y int) bool {
221
212
q = append(q, pair{node.Right, node})
222
213
}
223
214
}
224
- d++
225
215
}
226
- return p1 != p2 && d1 == d2
216
+ return d1 == d2 && p1 != p2
217
+ }
218
+ ```
219
+
220
+ ``` ts
221
+ /**
222
+ * Definition for a binary tree node.
223
+ * class TreeNode {
224
+ * val: number
225
+ * left: TreeNode | null
226
+ * right: TreeNode | null
227
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
228
+ * this.val = (val===undefined ? 0 : val)
229
+ * this.left = (left===undefined ? null : left)
230
+ * this.right = (right===undefined ? null : right)
231
+ * }
232
+ * }
233
+ */
234
+
235
+ function isCousins(root : TreeNode | null , x : number , y : number ): boolean {
236
+ let [d1, d2] = [0 , 0 ];
237
+ let [p1, p2] = [null , null ];
238
+ const q: [TreeNode , TreeNode ][] = [[root , null ]];
239
+ for (let depth = 0 ; q .length > 0 ; ++ depth ) {
240
+ const t: [TreeNode , TreeNode ][] = [];
241
+ for (const [node, parent] of q ) {
242
+ if (node .val === x ) {
243
+ [d1 , p1 ] = [depth , parent ];
244
+ } else if (node .val === y ) {
245
+ [d2 , p2 ] = [depth , parent ];
246
+ }
247
+ if (node .left ) {
248
+ t .push ([node .left , node ]);
249
+ }
250
+ if (node .right ) {
251
+ t .push ([node .right , node ]);
252
+ }
253
+ }
254
+ q .splice (0 , q .length , ... t );
255
+ }
256
+ return d1 === d2 && p1 !== p2 ;
227
257
}
228
258
```
229
259
230
260
<!-- tabs: end -->
231
261
232
262
### 方法二:DFS
233
263
234
- 我们设计一个函数 $dfs(root, fa, d )$,表示从根节点 $root$ 出发,其父节点为 $fa $,深度为 $d $,进行深度优先搜索。
264
+ 我们设计一个函数 $dfs(root, parent, depth )$,表示从根节点 $root$ 出发,其父节点为 $parent $,深度为 $depth $,进行深度优先搜索。
235
265
236
- 在函数中,我们首先判断当前节点是否为空,如果为空,则直接返回。如果当前节点的值为 $x$ 或 $y$,则记录该节点的父节点和深度。然后对当前节点的左右子节点分别调用函数 $dfs$,其中父节点为当前节点,深度为当前深度加 $1$。即 $dfs(root.left, root, d + 1)$ 和 $dfs(root.right, root, d + 1)$。
266
+ 在函数中,我们首先判断当前节点是否为空,如果为空,则直接返回。如果当前节点的值为 $x$ 或 $y$,则记录该节点的父节点和深度。然后对当前节点的左右子节点分别调用函数 $dfs$,其中父节点为当前节点,深度为当前深度加 $1$。即 $dfs(root.left, root, depth + 1)$ 和 $dfs(root.right, root, depth + 1)$。
237
267
238
268
当整棵二叉树遍历完毕后,如果 $x$ 和 $y$ 的深度相同且父节点不同,则返回 $true$,否则返回 $false$。
239
269
@@ -250,19 +280,19 @@ func isCousins(root *TreeNode, x int, y int) bool {
250
280
# self.right = right
251
281
class Solution :
252
282
def isCousins (self , root : Optional[TreeNode], x : int , y : int ) -> bool :
253
- def dfs (root , fa , d ):
283
+ def dfs (root , parent , depth ):
254
284
if root is None :
255
285
return
256
286
if root.val == x:
257
- t [0 ] = (fa, d )
258
- if root.val == y:
259
- t [1 ] = (fa, d )
260
- dfs(root.left, root, d + 1 )
261
- dfs(root.right, root, d + 1 )
287
+ st [0 ] = (parent, depth )
288
+ elif root.val == y:
289
+ st [1 ] = (parent, depth )
290
+ dfs(root.left, root, depth + 1 )
291
+ dfs(root.right, root, depth + 1 )
262
292
263
- t = [None , None ]
293
+ st = [None , None ]
264
294
dfs(root, None , 0 )
265
- return t [0 ][0 ] != t [1 ][0 ] and t [0 ][1 ] == t [1 ][1 ]
295
+ return st [0 ][0 ] != st [1 ][0 ] and st [0 ][1 ] == st [1 ][1 ]
266
296
```
267
297
268
298
``` java
@@ -283,8 +313,8 @@ class Solution:
283
313
*/
284
314
class Solution {
285
315
private int x, y;
286
- private TreeNode p1, p2;
287
316
private int d1, d2;
317
+ private TreeNode p1, p2;
288
318
289
319
public boolean isCousins (TreeNode root , int x , int y ) {
290
320
this . x = x;
@@ -293,20 +323,19 @@ class Solution {
293
323
return p1 != p2 && d1 == d2;
294
324
}
295
325
296
- private void dfs (TreeNode root , TreeNode p , int d ) {
326
+ private void dfs (TreeNode root , TreeNode parent , int depth ) {
297
327
if (root == null ) {
298
328
return ;
299
329
}
300
330
if (root. val == x) {
301
- p1 = p;
302
- d1 = d;
303
- }
304
- if (root. val == y) {
305
- p2 = p;
306
- d2 = d;
331
+ d1 = depth;
332
+ p1 = parent;
333
+ } else if (root. val == y) {
334
+ d2 = depth;
335
+ p2 = parent;
307
336
}
308
- dfs(root. left, root, d + 1 );
309
- dfs(root. right, root, d + 1 );
337
+ dfs(root. left, root, depth + 1 );
338
+ dfs(root. right, root, depth + 1 );
310
339
}
311
340
}
312
341
```
@@ -326,22 +355,22 @@ class Solution {
326
355
class Solution {
327
356
public:
328
357
bool isCousins(TreeNode* root, int x, int y) {
329
- TreeNode * p1, * p2;
330
358
int d1, d2;
331
- function<void(TreeNode* , TreeNode* , int)> dfs = [ &] (TreeNode* root, TreeNode* fa, int d) {
359
+ TreeNode* p1;
360
+ TreeNode* p2;
361
+ function<void(TreeNode* , TreeNode* , int)> dfs = [ &] (TreeNode* root, TreeNode* parent, int depth) {
332
362
if (!root) {
333
363
return;
334
364
}
335
365
if (root->val == x) {
336
- p1 = fa;
337
- d1 = d;
366
+ d1 = depth;
367
+ p1 = parent;
368
+ } else if (root->val == y) {
369
+ d2 = depth;
370
+ p2 = parent;
338
371
}
339
- if (root->val == y) {
340
- p2 = fa;
341
- d2 = d;
342
- }
343
- dfs(root->left, root, d + 1);
344
- dfs(root->right, root, d + 1);
372
+ dfs(root->left, root, depth + 1);
373
+ dfs(root->right, root, depth + 1);
345
374
};
346
375
dfs(root, nullptr, 0);
347
376
return p1 != p2 && d1 == d2;
@@ -359,24 +388,57 @@ public:
359
388
* }
360
389
*/
361
390
func isCousins(root *TreeNode, x int, y int) bool {
362
- var p1, p2 *TreeNode
363
391
var d1, d2 int
364
- var dfs func(*TreeNode, *TreeNode, int)
365
- dfs = func(root *TreeNode, fa *TreeNode, d int) {
392
+ var p1, p2 *TreeNode
393
+ var dfs func(root, parent *TreeNode, depth int)
394
+ dfs = func(root, parent *TreeNode, depth int) {
366
395
if root == nil {
367
396
return
368
397
}
369
398
if root.Val == x {
370
- p1, d1 = fa, d
399
+ d1, p1 = depth, parent
400
+ } else if root.Val == y {
401
+ d2, p2 = depth, parent
371
402
}
372
- if root.Val == y {
373
- p2, d2 = fa, d
374
- }
375
- dfs(root.Left, root, d+1)
376
- dfs(root.Right, root, d+1)
403
+ dfs(root.Left, root, depth+1)
404
+ dfs(root.Right, root, depth+1)
377
405
}
378
406
dfs(root, nil, 0)
379
- return p1 != p2 && d1 == d2
407
+ return d1 == d2 && p1 != p2
408
+ }
409
+ ```
410
+
411
+ ``` ts
412
+ /**
413
+ * Definition for a binary tree node.
414
+ * class TreeNode {
415
+ * val: number
416
+ * left: TreeNode | null
417
+ * right: TreeNode | null
418
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
419
+ * this.val = (val===undefined ? 0 : val)
420
+ * this.left = (left===undefined ? null : left)
421
+ * this.right = (right===undefined ? null : right)
422
+ * }
423
+ * }
424
+ */
425
+
426
+ function isCousins(root : TreeNode | null , x : number , y : number ): boolean {
427
+ let [d1, d2, p1, p2] = [0 , 0 , null , null ];
428
+ const dfs = (root : TreeNode | null , parent : TreeNode | null , depth : number ) => {
429
+ if (! root ) {
430
+ return ;
431
+ }
432
+ if (root .val === x ) {
433
+ [d1 , p1 ] = [depth , parent ];
434
+ } else if (root .val === y ) {
435
+ [d2 , p2 ] = [depth , parent ];
436
+ }
437
+ dfs (root .left , root , depth + 1 );
438
+ dfs (root .right , root , depth + 1 );
439
+ };
440
+ dfs (root , null , 0 );
441
+ return d1 === d2 && p1 !== p2 ;
380
442
}
381
443
```
382
444
0 commit comments