设为首页 加入收藏

TOP

[leetcode]Symmetric Tree @ Python
2015-07-20 17:35:52 来源: 作者: 【 】 浏览:2
Tags:leetcode Symmetric Tree Python
题意:判断二叉树是否为对称的。
?
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函数,当然也是递归的。当存在左右子树时,判断左右子树的根节点值是否相等,如果想等继续递归判断左子树根的右子树根节点和右子树根的左子树根节点以及左子树根的左子树根节点和右子树根的右子树根节点的值是否相等。然后一直递归判断下去就可以了。
?
?
?
复制代码
# 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 isSymmetric(self, root):
? ? ? ? if root:
? ? ? ? ? ? return self.help(root.left, root.right)
? ? ? ? return True
? ? ? ??
? ? def help(self, p,q):
? ? ? ? if p is None and q is None: return True
? ? ? ? if p and q and p.val == q.val:
? ? ? ? ? ? return self.help(p.left, q.right) and self.help(p.right, q.left)
? ? ? ? return False
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇NYOJ 1085 数单词 (AC自动机模板.. 下一篇poj 递增栈 POJ2796 区间最大参考..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·透彻理解 C 语言指针 (2025-12-26 00:22:52)
·C语言指针详解 (经典 (2025-12-26 00:22:49)
·C 指针 | 菜鸟教程 (2025-12-26 00:22:46)
·PostgreSQL 索引 - (2025-12-25 22:20:43)
·MySQL Node.js 连接 (2025-12-25 22:20:41)