Leetcode联系:对称二叉树,python实现

采用迭代方法,按从左到右的节点一层层判断是否对称,如果对称则继续判断下一层,直到遇到不对称的点或没有下一层为止。

每层从首位向中间遍历,如果两个节点都是Null,或者两个节点不是Null且值相同(注意子节点有可能不同),则为对称;否则为不对称跳出循环。

这里有一个需要注意的点,就是如何处理Null节点。处理方法是:构建下一层时,仍然将Null当做节点放入列表;但不将Null的子节点放入列表。这样做的思想是:当处理当前层时,上面的层是对称的(否则在上面就已经跳出循环了),因此不将Null的子节点放入下一层列表不会导致下一层的节点连接关系混乱。因为如果此层是对称的,那下一层缺失的部分也是对称的;如果此层不是对称的,则在此层就会跳出循环。

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# diedai
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        if not root.left and not root.right:
            return True
        # All the node in the same level
        current_level = [root]
        # value to return
        is_symmetric = True
        
        while(len(current_level) > 0 and is_symmetric):
            new_level = []
            for current_node in current_level:
                # only append when the node is valid.
                if current_node:
                    new_level.append(current_node.left)
                    new_level.append(current_node.right)
            
            half = int(len(new_level)/2)
            for i in range(0, half):
                # if both are Null, is symmetric
                if not new_level[i] and not new_level[-i-1]:
                    continue
                # if both are not Null, and the values are same, is symmetric
                elif new_level[i] and new_level[-i-1] and new_level[i].val == new_level[-i-1].val:
                    continue
                else:
                    is_symmetric = False
                    break
            current_level = new_level
        return is_symmetric

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值