101. Symmetric Tree(59 对称的二叉树)

1、题意:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

2、分析和解答
(1)我的想法,是通过数组的长度计算出树的高度,由于没法使用log2函数,没实现。元素个数和行数是有关系的:1,2,4,8。。。
(2)关于树的方法,没想出来!!!看了答案后了然。第一种好比照镜子那样,是一个递归的算法,终止条件是:这两个节点的值都为null。在镜子中,人的左手表现的是右手,所以只需要递归地进行根的左孩子和根的右孩子,以及根的右孩子及左孩子即可。代码如下:

 boolean isMirror(TreeNode root1,TreeNode root2){
        if(root1 == null && root2 == null)
            return true;
        if(root1 == null || root2 == null)//***
            return false;
        if(root1.val == root2.val && 
                    isMirror(root1.left,root2.right) && 
                    isMirror(root1.right,root2.left)){
            return true;
        }        
        return false;
    }
    public boolean isSymmetric(TreeNode root) {
         return isMirror(root,root);
    }

后面标注“*”的那一点容易忽略,当有一个root的孩子为null的时候,获得它的val时,会导致NULL指针异常!!!解决方法就是只要有一个为null(此时已经排除了都为null的条件了),就返回false。
由于遍历的是整个树中的节点,所以时间复杂度是O(n);在最差的情况下,是指树是线性的,这时候高度为n,空间复杂度也为O(n)。
注意:是判断root1.val 和root2.val是否相等,而不是两个root!
2、第二种方法是循环到方法,其实就是BFS(层次遍历),使用一个队列完成对两个数的对比,关键是两棵树的入队顺序正好相反,与递归的思想其实相同。代码如下:

public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        LinkedList<TreeNode> queue = new LinkedList();
        queue.add(root);
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode n1 = queue.remove();
            TreeNode n2 = queue.remove();
            if(n1 == null && n2 == null)
                continue;
            if(n1 == null || n2 == null)
                return false;
            if(n1.val != n2.val)
                return false;
            queue.add(n1.left);     
            queue.add(n2.right);      
            queue.add(n1.right);            
            queue.add(n2.left);
        }

        return true;
    }

Note:也是需要判断出队后的节点为NULL的情况,都为null还是一个为NULL,因为下面有引用的值,可能会出现null指针异常!
注意:关于队列,一般使用LinkedList来实现,Queue<TreeNode> q = new LinkedList<>();有两个API常用:offer(),poll();peek()
linkedList也有两个常用API:add() , remove();
层次遍历很简单,先入队,然后进入循环,再出队visit,再入对!!!
和先序遍历很像,无非那个是入栈,先入右孩子再入左孩子!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值