剑指28 对称二叉树

82 阅读1分钟

对称二叉树

在这里插入图片描述
思路:
自顶向下递归
判断左右两侧对应位置是否对称
即:左空 and 右空:对称
左右只有一个None:不对称
左右对应节点值不等:不对称
递归:左节点左子节点值=右节点右子节点值
左节点右子节点值=右节点左子节点值

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def helper(L,R):
            if not L and not R:return True
            if not L or not R:return False
            if L.val!=R.val:return False
            return helper(L.right,R.left) and helper(L.left,R.right)
        if not root:return True
        return helper(root.left,root.right)