# Symmetric Tree

187人阅读 评论(0)

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.

public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
return BothIsSymmetric(root.left, root.right);
}

public boolean BothIsSymmetric(TreeNode root1,TreeNode root2) {
if(root1==null&&root2==null)
return true;
if((root1==null^root2==null)||(root1!=null&&root2!=null&&root1.val!=root2.val))
return false;
return BothIsSymmetric(root1.left, root2.right)&&BothIsSymmetric(root1.right, root2.left);
}

enum Child{
left,right;
}

class NewNode{
TreeNode root;
TreeNode parent;
Child child;

public NewNode(TreeNode root,TreeNode parent,Child child){
this.root=root;
this.parent=parent;
this.child=child;
}
}
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
Deque<NewNode> leftQueue=new ArrayDeque<NewNode>();
Deque<NewNode> rightQueue=new ArrayDeque<NewNode>();
if(root.left!=null)
leftQueue.offer(new NewNode(root.left, root, Child.left));
if(root.right!=null)
rightQueue.offer(new NewNode(root.right, root, Child.right));
while(!leftQueue.isEmpty()&&!rightQueue.isEmpty()){
NewNode leftNewNode=leftQueue.poll();
NewNode rightNewNode=rightQueue.poll();
if(leftNewNode.root.val!=rightNewNode.root.val||leftNewNode.child==rightNewNode.child||leftNewNode.parent!=rightNewNode.parent)
return false;
if(leftNewNode.root.left!=null)
leftQueue.offer(new NewNode(leftNewNode.root.left,leftNewNode.root,Child.left));
if(leftNewNode.root.right!=null)
leftQueue.offer(new NewNode(leftNewNode.root.right,leftNewNode.root,Child.right));
if(rightNewNode.root.right!=null)
rightQueue.offer(new NewNode(rightNewNode.root.right,rightNewNode.root,Child.right));
if(rightNewNode.root.left!=null)
rightQueue.offer(new NewNode(rightNewNode.root.left,rightNewNode.root,Child.left));
}
if(leftQueue.isEmpty()&&rightQueue.isEmpty())
return true;
return false;
}

public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
leftQueue.push(root.left);
rightQueue.push(root.right);
while(!leftQueue.isEmpty()&&!rightQueue.isEmpty()){
TreeNode leftnode=leftQueue.poll();
TreeNode rightnode=rightQueue.poll();
if(leftnode==null&&rightnode==null)
continue;
if(leftnode==null||rightnode==null)
return false;
if(leftnode.val!=rightnode.val)
return false;
leftQueue.push(leftnode.left);
leftQueue.push(leftnode.right);
rightQueue.push(rightnode.right);
rightQueue.push(rightnode.left);
}
if(leftQueue.isEmpty()&&rightQueue.isEmpty())
return true;
return false;
}

0
0

个人资料
• 访问：64062次
• 积分：2776
• 等级：
• 排名：第15296名
• 原创：215篇
• 转载：37篇
• 译文：0篇
• 评论：6条
最新评论