zoukankan      html  css  js  c++  java
  • 16.leetcode101_symmetric_tree

    1.题目描述

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

    判断输入的树杈是否是镜像结构

    2.题目分析

    判断给出的树杈每一级对应的左节点与右节点是否相同

    3.解题思路

    从头开始判断下一级的左节点与右节点是否相同

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 class Solution(object):
     8     def isSymmetric(self, root):
     9         """
    10         :type root: TreeNode
    11         :rtype: bool
    12         """
    13         def ismirror(node1,node2):  #自定义函数ismirror判断节点是否对称
    14             if node1==None and node2==None: #判断节点结构是否相同
    15                 return True
    16             elif node1==None or node2==None:
    17                 return False
    18             else:  #判断数据域是否相同
    19                 if node1.val!=node2.val:
    20                     return False
    21                 else: #节点相同的情况下分析下一级
    22                     return ismirror(node1.left,node2.right) and ismirror(node1.right,node2.left)
    23         if root==None: #判断是否为空树杈
    24             return True
    25         else: #不是空树杈的情况下调用自定义的ismirror函数
    26             return ismirror(root.left,root.right)

    4.解题收获

    与leetcode100th题思路相同,通过这两个题进一步加强了对于链表的理解

  • 相关阅读:
    C
    B
    A
    G
    BZOJ_1208_&_Codevs_1258_[HNOI2004]_宠物收养所_(平衡树/set)
    Codevs_1230_元素查找_(set/Hash)
    POJ_2503_Babelfish_(Trie/map)
    POJ_2001_Shortest_Prefixes_(Trie)
    BZOJ_3670_[NOI2014]_动物园_(kmp)
    BZOJ_3196_二逼平衡树_(树套树,线段树+Treap)
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8428718.html
Copyright © 2011-2022 走看看