@@ -360,6 +360,78 @@ Java:
360
360
361
361
Python:
362
362
363
+ > 递归法
364
+ ``` python
365
+ class Solution :
366
+ def isSymmetric (self , root : TreeNode) -> bool :
367
+ if not root:
368
+ return True
369
+ return self .compare(root.left, root.right)
370
+
371
+ def compare (self , left , right ):
372
+ # 首先排除空节点的情况
373
+ if left == None and right != None : return False
374
+ elif left != None and right == None : return False
375
+ elif left == None and right == None : return True
376
+ # 排除了空节点,再排除数值不相同的情况
377
+ elif left.val != right.val: return False
378
+
379
+ # 此时就是:左右节点都不为空,且数值相同的情况
380
+ # 此时才做递归,做下一层的判断
381
+ outside = self .compare(left.left, right.right) # 左子树:左、 右子树:右
382
+ inside = self .compare(left.right, right.left) # 左子树:右、 右子树:左
383
+ isSame = outside and inside # 左子树:中、 右子树:中 (逻辑处理)
384
+ return isSame
385
+ ```
386
+
387
+ > 迭代法: 使用队列
388
+ ``` python
389
+ import collections
390
+ class Solution :
391
+ def isSymmetric (self , root : TreeNode) -> bool :
392
+ if not root:
393
+ return True
394
+ queue = collections.deque()
395
+ queue.append(root.left) # 将左子树头结点加入队列
396
+ queue.append(root.right) # 将右子树头结点加入队列
397
+ while queue: # 接下来就要判断这这两个树是否相互翻转
398
+ leftNode = queue.popleft()
399
+ rightNode = queue.popleft()
400
+ if not leftNode and not rightNode: # 左节点为空、右节点为空,此时说明是对称的
401
+ continue
402
+
403
+ # 左右一个节点不为空,或者都不为空但数值不相同,返回false
404
+ if not leftNode or not rightNode or leftNode.val != rightNode.val:
405
+ return False
406
+ queue.append(leftNode.left) # 加入左节点左孩子
407
+ queue.append(rightNode.right) # 加入右节点右孩子
408
+ queue.append(leftNode.right) # 加入左节点右孩子
409
+ queue.append(rightNode.left) # 加入右节点左孩子
410
+ return True
411
+ ```
412
+
413
+ > 迭代法:使用栈
414
+ ``` python
415
+ class Solution :
416
+ def isSymmetric (self , root : TreeNode) -> bool :
417
+ if not root:
418
+ return True
419
+ st = [] # 这里改成了栈
420
+ st.append(root.left)
421
+ st.append(root.right)
422
+ while st:
423
+ leftNode = st.pop()
424
+ rightNode = st.pop()
425
+ if not leftNode and not rightNode:
426
+ continue
427
+ if not leftNode or not rightNode or leftNode.val != rightNode.val:
428
+ return False
429
+ st.append(leftNode.left)
430
+ st.append(rightNode.right)
431
+ st.append(leftNode.right)
432
+ st.append(rightNode.left)
433
+ return True
434
+ ```
363
435
364
436
Go:
365
437
0 commit comments