leetcode101对称二叉树

leetcode101 Symmetric Tree

Posted by BY on March 20, 2019

前言

新的一年,好好学习。尝试用python写写代码。

正文

问题来源

本问题来自leetcode上的101题。

问题描述

给定一个二叉树,检查它是否是镜像对称的。

示例 1:

二叉树 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3    

示例 2:

二叉树 [1,2,2,3,4,4,3] 是对称的。

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

分析:

递归版本(自己写的)

# 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
        """
        if None == root :
            return True
        return self.isSymmetric2(root.left, root.right)
    def isSymmetric2(self,node1,node2):
        if None == node1 and None == node2 :
            return True
        elif None == node1 or None == node2 :
            return False
        if node1.val != node2.val :
            return False
        return self.isSymmetric2(node1.left, node2.right) and self.isSymmetric2(node1.right, node2.left)

非递归版(别人)

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        
        stack=[[root.left,root.right]]
        while stack:
            left,right=stack.pop()
            if not left and not right:
                continue
            
            if not left or not right or left.val!=right.val:
                return False
            
            if left.left or right.right:
                stack.append([left.left,right.right])
            if left.right or right.left:
                stack.append([left.right,right.left])
        return True

“stack=[[root.left,root.right]]”可以理解为list的list;“left,right=stack.pop()”直接获取list的list里的单个数据。
“stack.append([left.left,right.right])”直接加入一个list。

总结:

勤思考。
Python不支持方法的重载。判断指针是否为空可以使用如: “if node:” “while stack:” 语句。
Python调用本类中的函数,需要使用self关键字;而java,C++等不需要使用this关键字。
Python的逻辑操作有三种:and、or、not。分别对应与、或、非。

结语

不管怎么样好好加油。