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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenchaofuck1/article/details/51287907

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;
    }


没有更多推荐了,返回首页