题目:
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? > read more on how binary tree is serialized on OJ.
链接:http://leetcode.com/submissions/detail/11328058/
一刷
recursive
1 def isSymmetric(p, q): 2 if not p and not q: 3 return True 4 if not p or not q: 5 return False 6 7 return p.val == q.val and isSymmetric(p.left, q.right) and isSymmetric(p.right, q.left) 8 9 class Solution(object): 10 def isSymmetric(self, root): 11 if not root: 12 return True 13 return isSymmetric(root.left, root.right)
iterative,利用tuple来成对比较,答案是抄的。。。
1 class Solution(object): 2 def isSymmetric(self, root): 3 if not root: 4 return True 5 stack = [(root.left, root.right)] 6 7 while stack: 8 l_elem, r_elem = stack.pop() 9 if not l_elem and not r_elem: 10 continue 11 if not l_elem or not r_elem: 12 return False 13 if l_elem.val == r_elem.val: 14 stack.extend([(l_elem.left, r_elem.right), (l_elem.right, r_elem.left)]) 15 else: 16 return False 17 return True
参考:
https://leetcode.com/discuss/14944/recursively-and-iteratively-solution-in-python
2/16/2017, Java
performance不够好,二刷再解决
1 public class Solution { 2 public boolean isSymmetric(TreeNode root) { 3 if (root == null || root.left == null && root.right == null) return true; 4 return isSymmetric(root.left, root.right); 5 } 6 private boolean isSymmetric(TreeNode p, TreeNode q) { 7 if (p == null && q == null) return true; 8 if (p == null && q != null || p != null && q == null || p.val != q.val) return false; 9 if (isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left)) return true; 10 return false; 11 } 12 }