首页 > 其他 > 详细

16.leetcode101_symmetric_tree

时间:2018-02-07 23:17:56      阅读:240      评论:0      收藏:0      [点我收藏+]

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题思路相同,通过这两个题进一步加强了对于链表的理解

16.leetcode101_symmetric_tree

原文:https://www.cnblogs.com/19991201xiao/p/8428718.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!