对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
提示:
- 树中节点数目在范围
[1, 1000]
内 -100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
emmm...
用了递归,对于树的题目能用递归则用递归...qwq
就是对称着去判断,代码可能看着长而繁...(越来越觉得内置函数好用了...
# 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:
real = True
def func(left,right):
if left!=None and right== None or left==None and right!=None:return False
if left and right and left.val != right.val:return False
if left and right:return func(left.left,right.right) and func(left.right,right.left)
else:return True
if root == None:return True
return func(root.left,root.right)