Problem
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Algorithm
Recursion. If a trees is mirror of itself, the left sub-tree’s left sub-tree is mirror of the right sub-tree’s right sub-tree and the left sub-tree’s right sub-tree is mirror of the right sub-tree’s left sub-tree.
Code
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def isSymmetric(L, R):
if L and R:
if L.val == R.val:
return isSymmetric(L.left, R.right) and isSymmetric(L.right, R.left)
else:
return False
elif not L and not R:
return True
else:
return False
if root:
return isSymmetric(root.left, root.right)
return True
本文介绍了一种通过递归方法判断给定二叉树是否镜像自身的算法。通过比较左右子树的对称关系,代码展示了如何检查每层节点是否对称。适用于对数据结构和递归理解的应用开发者。
410

被折叠的 条评论
为什么被折叠?



