【leetcode-树】对称二叉树

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

递归实现:
 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) {
            return true;
        }
        
        return isSymmetric(root.left, root.right);

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

    }
}

非递归实现:采用层次遍历,注意空节点也要加入队列

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.LinkedList;
import java.util.ArrayList;
public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        if(pRoot == null)
            return true;
        LinkedList<TreeNode> list = new LinkedList<>();
        list.addLast(pRoot);
        while(list.size() > 0){
            ArrayList<Integer> listVal = new ArrayList<>(); 
            int len = list.size();
            for(int i = 0; i < len;i ++){
                TreeNode node = list.pollFirst();
                if(node != null){
                    list.addLast(node.left);//无论左右子树是否为空,都要加入
                    list.addLast(node.right);
                    listVal.add(node.val);       
                }
                else
                    listVal.add(null); //空节点也要加入null,起占位作用
            }

            //双指针判断是否对称
            int l = 0;
            int h = listVal.size() - 1;
                while(l < h){
                    if(listVal.get(l) != listVal.get(h))
                        return false;
                    else{
                        l ++;
                        h --;
                    }
                }
        }
        return true;
    }
}
发布了196 篇原创文章 · 获赞 212 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/kangbin825/article/details/105023220
今日推荐