[Leetcode]Symmetric Tree
来源:互联网 发布:excel数据对比分析 编辑:程序博客网 时间:2024/05/17 08:29
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
Note:
Bonus points if you could solve it both recursively and iteratively.
判断数是否对称~不对称的条件有以下三个:(1)左边为空而右边不为空;(2)左边不为空而右边为空;(3)左边值不等于右边值~算法的时间复杂度是树的遍历O(n),空间复杂度同样与树遍历相同是O(logn)~ (写关于树的题目还是不太熟练,还得加强练习)递归代码如下~
class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if root is None: return True return self.helper(root.left, root.right) def helper(self, root1, root2): if root1 is None and root2 is None: return True if root1 is None or root2 is None: return False if root1.val != root2.val: return False return self.helper(root1.left, root2.right) and self.helper(root1.right, root2.left)
参考了别人的代码,非递归解法如下~ (非递归解法要自己写还真是有点写不出来,加油吧~)
class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if root is None: return True queue = [[root.left, root.right]] while queue: pair = queue.pop(0) if not (pair[0] or pair[1]): continue elif (pair[0] and pair[1]) and pair[0].val == pair[1].val: queue.append([pair[0].left, pair[1].right]) queue.append([pair[0].right, pair[1].left]) else: return False return True
0 0
- Leetcode - Tree - Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- LeetCode[Tree]: Symmetric Tree
- [leetcode][tree] Symmetric Tree
- LeetCode: Symmetric Tree
- [Leetcode] Symmetric Tree
- LeetCode : Symmetric Tree
- leetcode 13:symmetric tree
- [LeetCode] Symmetric Tree - Recursively
- [LeetCode] Symmetric Tree - Iteratively
- [LeetCode] Symmetric Tree
- [LeetCode]Symmetric Tree
- Leetcode:Symmetric Tree
- [Leetcode]Symmetric Tree
- Leetcode: Symmetric Tree
- [leetcode]Symmetric Tree
- LeetCode-Symmetric Tree
- [leetcode] Symmetric Tree
- Apache配置
- Ubuntu下Eclipse安装SVN插件(Subversion & Subclipse)
- 当遇到用\来分隔字符串
- Scrapy下xpath基本的使用方法
- Python Interview Questions: A Review
- [Leetcode]Symmetric Tree
- php DOM 解析
- 关于一个社交类App 技术选型备忘
- 微博开放平台SDK使用
- Mail signature reverts to old value after template upgrade to 8.5.2
- Jquery 判断滚动条到达顶部或底部 (可用于上拉下拉加载刷新)
- 图像之二维高斯核
- Debug目录、Release目录,bin目录、obj目录,vshost.exe.config文件、.exe.config文件分析【C#】
- 详解slab机制