Leetcode[101] Symmetric Tree
07 Nov 2015###Task1 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
###Python ####Recursive
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.isValid(root.left, root.right)
def isValid(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return self.isValid(left.left, right.right) and self.isValid(left.right, right.left)
####Iterative
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
leftQ = collections.deque()
rightQ = collections.deque()
leftQ.append(root.left)
rightQ.append(root.right)
while len(leftQ) > 0 or len(rightQ) > 0:
l = leftQ.popleft()
r = rightQ.popleft()
if not l and not r:
continue
if not l or not r:
return False
if l.val != r.val:
return False
leftQ.append(l.left)
leftQ.append(l.right)
rightQ.append(r.right)
rightQ.append(r.left)
return True
###Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) {
return true;
}
if (root.left == null || root.right == null) {
return false;
}
Queue<TreeNode> leftQueue = new LinkedList<TreeNode>();
Queue<TreeNode> rightQueue = new LinkedList<TreeNode>();
leftQueue.offer(root.left);
rightQueue.offer(root.right);
while (!leftQueue.isEmpty() && !rightQueue.isEmpty()) {
TreeNode left = leftQueue.poll();
TreeNode right = rightQueue.poll();
if (left == null && right == null) {
continue;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return false;
} else {
leftQueue.offer(left.left);
leftQueue.offer(left.right);
rightQueue.offer(right.right);
rightQueue.offer(right.left);
}
}
return true;
}
}
###Points
- Divide and conquer
- O(n)
- Python Queue: collections.deque() -> q.popleft()