题目¶
原题地址:https://leetcode.com/problems/symmetric-tree/
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
Follow up: Solve it both recursively and iteratively.
解法¶
从上到下一层一层进行比较。
这个方法的 Python 代码类似下面这样:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
return self.is_mirror(root.left, root.right)
def is_mirror(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return self.is_mirror(left.left, right.right) and self.is_mirror(left.right, right.left)
Comments