您的位置:首页 > 其它

Symmetric Tree

2015-08-02 08:05 447 查看
题目:

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.

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}"
.

题解

判断左右子树是否对称。

解法一:递归的解法:

 public boolean isSymmetricTree(TreeNode p,TreeNode q){
if(p == null&&q == null)
return true;
if(p == null||q == null)
return false;
return (p.val == q.val) && isSymmetricTree(p.left, q.right) && isSymmetricTree(p.right, q.left);
}

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

return isSymmetricTree(root.left,root.right);
}


解法二:非递归解法:

 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;
LinkedList<TreeNode> q1 = new LinkedList<TreeNode>();
LinkedList<TreeNode> q2 = new LinkedList<TreeNode>();
q1.add(root.left);
q2.add(root.right);
while(!q1.isEmpty() && !q2.isEmpty()){
TreeNode n1 = q1.poll();
TreeNode n2 = q2.poll();

if(n1.val != n2.val)
return false;
if((n1.left == null && n2.right != null) || (n1.left != null && n2.right == null))
return false;
if((n1.right == null && n2.left != null) || (n1.right != null && n2.left == null))
return false;

if(n1.left != null && n2.right != null){
q1.add(n1.left);
q2.add(n2.right);
}

if(n1.right != null && n2.left != null){
q1.add(n1.right);
q2.add(n2.left);
}
}
return true;
}


reference:
http://blog.csdn.net/linhuanmars/article/details/23072829
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: