diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 1eb43589..caf5d249 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -437,6 +437,31 @@ class Solution: return True ``` +层次遍历 +```python +class Solution: + def isSymmetric(self, root: Optional[TreeNode]) -> bool: + if not root: + return True + + que = [root] + while que: + this_level_length = len(que) + for i in range(this_level_length // 2): + # 要么其中一个是None但另外一个不是 + if (not que[i] and que[this_level_length - 1 - i]) or (que[i] and not que[this_level_length - 1 - i]): + return False + # 要么两个都不是None + if que[i] and que[i].val != que[this_level_length - 1 - i].val: + return False + for i in range(this_level_length): + if not que[i]: continue + que.append(que[i].left) + que.append(que[i].right) + que = que[this_level_length:] + return True +``` + ## Go ```go