LeetCode101——Symmetric Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28306361/article/details/88016742

题目链接

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

同样的,还是用递归的思路,对于最初的根节点,只需要比较它的左右子树是否对称,对于左右子节点, 只需要左子节点的右子树和右子节点的左子树是否相同, 并且左子节点的左子树和右子节点的右子树是否相同,代码如下:

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root == None:
            return True
        return self.checkTwoTreeNodes(root.left, root.right)

    def checkTwoTreeNodes(self, p:TreeNode, q:TreeNode) -> bool:
        if p == None and q == None:
            return True
        if p == None and q != None or p != None and q == None:
            return False

        if p.val != q.val:
            return False
        return self.checkTwoTreeNodes(p.left, q.right) and self.checkTwoTreeNodes(p.right, q.left)

测评结果

Runtime: 44 ms, faster than 60.85% of Python3 online submissions for Symmetric Tree.
Memory Usage: 13.2 MB, less than 5.61% of Python3 online submissions for Symmetric Tree.

猜你喜欢

转载自blog.csdn.net/qq_28306361/article/details/88016742