1. 程式人生 > >leetcode 101. Symmetric Tree 判斷對稱樹,遞迴和迭代

leetcode 101. Symmetric Tree 判斷對稱樹,遞迴和迭代

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