BiruLyu
5/25/2017 - 4:52 PM

## 101. Symmetric Tree(#1 Recursive).java

``````public boolean isSymmetric(TreeNode root) {
if(root==null)  return true;

Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode left, right;
if(root.left!=null){
if(root.right==null) return false;
stack.push(root.left);
stack.push(root.right);
}
else if(root.right!=null){
return false;
}

while(!stack.empty()){
if(stack.size()%2!=0)   return false;
right = stack.pop();
left = stack.pop();
if(right.val!=left.val) return false;

if(left.left!=null){
if(right.right==null)   return false;
stack.push(left.left);
stack.push(right.right);
}
else if(right.right!=null){
return false;
}

if(left.right!=null){
if(right.left==null)   return false;
stack.push(left.right);
stack.push(right.left);
}
else if(right.left!=null){
return false;
}
}

return true;
}``````
``````# 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 helper(self,left,right):
if not left and not right:
return True;
elif not left or not right:
return False;
elif left.val != right.val:
return False;
else:
return self.helper(left.left,right.right) and self.helper(left.right,right.left);

def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True;

return self.helper(root.left,root.right);

``````
``````
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) { return true; }
l.offer(root.left);
r.offer(root.right);
while(!l.isEmpty() && !r.isEmpty()) {
TreeNode a = l.poll(), b = r.poll();
if (a == null && b == null) continue;
if (a == null || b == null) return false;
if (a.val != b.val) return false;
l.offer(a.left);
r.offer(b.right);
l.offer(a.right);
r.offer(b.left);
}
return true;
}
}``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean helper(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null || root1.val != root2.val) return false;
return helper(root1.left, root2.right) && helper(root1.right, root2.left);
}
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return helper(root.left, root.right);
}
}``````