码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Symmetric Tree @ Python

时间:2014-05-26 10:18:52      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

原题地址:https://oj.leetcode.com/problems/symmetric-tree/

题意:判断二叉树是否为对称的。

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

For example, this binary tree is symmetric:

    1
   /   2   2
 / \ / 3  4 4  3

 

But the following is not:

    1
   /   2   2
   \      3    3

解题思路:这题也不难。需要用一个help函数,当然也是递归的。当存在左右子树时,判断左右子树的根节点值是否相等,如果想等继续递归判断左子树根的右子树根节点和右子树根的左子树根节点以及左子树根的左子树根节点和右子树根的右子树根节点的值是否相等。然后一直递归判断下去就可以了。

代码:

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

class Solution:
    # @param root, a tree node
    # @return a boolean
    def help(self, p, q):
        if p == None and q == None: return True
        if p and q and p.val == q.val:
            return self.help(p.right, q.left) and self.help(p.left, q.right)
        return False
    
    def isSymmetric(self, root):
        if root:
            return self.help(root.left, root.right)
        return True
bubuko.com,布布扣

 

[leetcode]Symmetric Tree @ Python,布布扣,bubuko.com

[leetcode]Symmetric Tree @ Python

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3747174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!