您的位置:首页 > 其它

leetcode 101. Symmetric Tree 判断对称树,递归和迭代

2016-04-30 21:23 453 查看
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


使用递归,判断代码如下:

public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
return isSymmetric(root.left,root.right);
}
public boolean isSymmetric(TreeNode l,TreeNode r){
if(l==null && r==null)
return true;
if(l==null || r==null)
return false;
if(l.val==r.val)
return isSymmetric(l.left,r.right) && isSymmetric(l.right,r.left);
return false;
}

使用迭代,广度优先使用队列,这里使用两个队列,分别代表根节点的左右孩子作为根的树,判断这两个队列是否对称。

public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
Queue<TreeNode> ql=new LinkedList<>();
Queue<TreeNode> qr=new LinkedList<>();
ql.offer(root.left);
qr.offer(root.right);
while(!ql.isEmpty() ){
TreeNode left=ql.poll();
TreeNode right=qr.poll();
if(left==null && right==null){
continue;
}
if(left==null || right==null || left.val!=right.val){
return false;
}
ql.offer(left.left);
ql.offer(left.right);
qr.offer(right.right);
qr.offer(right.left);
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: