Skip to content

101. Symmetric Tree

题目

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

 

Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

 

Follow up: Could you solve it both recursively and iteratively?
Related Topics
  • 深度优先搜索
  • 广度优先搜索
  • 二叉树

  • 👍 2975
  • 👎 0
  • 递归思路

    递归判断每个左右节点的数据是否相同,不同可以直接返回 False,终止递归判断

    解法

    python
    class Solution:
        def isSymmetric(self, root: Optional[TreeNode]) -> bool:
            def check(p: Optional[TreeNode], q:Optional[TreeNode]) -> bool:
                if not p and not q: return True
                if not p or not q: return False
                return p.val == q.val and check(p.left, q.right) and check(p.right, q.left)
    
            return check(root, root)

    复杂度分析

    • 时间复杂度 O(N)
    • 空间复杂度 O(N)

    迭代法

    广度优先遍历,注意点进入对列的顺序为

    • leftTreeNode.left

    • rightTreeNode.right

    • leftTreeNode.right

    • rightTreeNode.left

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def isSymmetric(self, root: Optional[TreeNode]) -> bool:
            def check(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
                quene = []
                quene.append(p)
                quene.append(q)
    
                while quene:
                    l = quene.pop(0)
                    r = quene.pop(0)
                    if not l and not r:
                        continue
                    if not l or not r:
                        return False
                    if l.val != r.val:
                        return False
    
                    quene.append(l.left)
                    quene.append(r.right)
    
                    quene.append(l.right)
                    quene.append(r.left)
    
                return True
    
            return check(root, root)
    
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(N)
    • 空间复杂度 O(N)