【LEETCODE】101-Symmetric Tree
来源:互联网 发布:黑马播放器 for mac 编辑:程序博客网 时间:2024/05/20 08:25
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.
confused what "{1,#,2,3}" means?
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
思路:
当 root.left == root.right 时,再去判断 root.left.left == root.right.right 和 root.left.right == root.right.left (只为记号,并不存在root.left.right之说)
然后再去递归判断 root.left.left vs root.right.right 作为root的时候,及 root.left.right vs root.right.left 作为root的时候
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def compare(self,p,q): #当两个node相等时,比较两个node作为根时的子树是否对称 if p == q == None: return True elif p and q and p.val == q.val: #[2,2] return self.compare(p.left,q.right) and self.compare(p.right,q.left) #[2,3,4] vs [2,4,3] else: return False def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root is None: return True else: #[1] return self.compare(root.left,root.right) #对称,需要比较两个root,所以需要写一个辅助函数
- LeetCode(101)Symmetric Tree
- LeetCode 101 Symmetric Tree
- LeetCode: Symmetric Tree [101]
- [leetcode 101] Symmetric Tree
- [LeetCode 101]Symmetric Tree
- leetcode-101 Symmetric Tree
- leetcode || 101、Symmetric Tree
- Leetcode[101]-Symmetric Tree
- leetcode[101]:Symmetric Tree
- LeetCode 101 Symmetric Tree
- leetcode 101 Symmetric Tree
- Leetcode# 101 Symmetric Tree
- leetcode 101: Symmetric Tree
- leetCode #101 Symmetric Tree
- leetcode-101-Symmetric Tree
- leetcode 101 Symmetric Tree
- LeetCode 101: Symmetric Tree
- 【LEETCODE】101-Symmetric Tree
- 入口
- soj 2309: In the Army Now (树状数组求逆序数)
- java基础测试(2)
- 葛爷带你上iOS王者——02
- 图的最小生成树prim算法详解
- 【LEETCODE】101-Symmetric Tree
- java学习:Graphics绘制基本图形对象
- hdu 3308 线段树+区间合并
- C++ 读写注册表
- frame、bounds和center
- javascript做导航条
- 关于php-echo原理
- hdu 1159 动态规划初步
- 项目三——稀疏矩阵的三元组表示的实现及应用