zoukankan      html  css  js  c++  java
  • 【力扣】101. 对称二叉树

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

    例如,二叉树 [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
     

    进阶:

    你可以运用递归和迭代两种方法解决这个问题吗?

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/symmetric-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    //---------------------------------我是递归----------------
        //如果当前树是对称的,那么其左右节点相等,左右节点下的子树对称
        public boolean isSymmetric(TreeNode root) {
            return def(root,root);
        }
    
    
        /**
        * 看了题解,这个思路真是绝了,遍历两个root
        **/
        public boolean def(TreeNode left,TreeNode right){
            if(left == null && right == null){
                return true;
            }
            if((left == null && right != null) || (left != null && right == null)){
                return false;
            }
            if(left.val != right.val){
                return false;
            }
            if(!def(left.left,right.right)){
                return false;
            }
            return def(left.right,right.left);
        }
    
        //时间复杂度O(n)
        //空间复杂度O(n)
    //---------------------------------我是迭代----------------
        //如果当前树是对称的,那么其左右节点相等,左右节点下的子树对称
        public boolean isSymmetric(TreeNode root) {
            if(root == null){
                return true;
            }
            Stack<TreeNode> stack1 = new Stack();
            stack1.push(root);
            Stack<TreeNode> stack2 = new Stack();
            stack2.push(root);
            while(!stack1.isEmpty() && !stack2.isEmpty()){
                TreeNode temp1 = stack1.pop();
                TreeNode temp2 = stack2.pop();
                if(temp1.val != temp2.val){
                    return false;
                }
                //判断空值是否相等
                if((temp1.left == null && temp2.right != null) || (temp1.left != null && temp2.right == null)){
                    return false;
                }
                if(temp1.left != null && temp2.right != null){
                    stack1.push(temp1.left);
                    stack2.push(temp2.right);
                }
                if(temp1.right != null && temp2.left != null){
                    stack1.push(temp1.right);
                    stack2.push(temp2.left);
                }
            }
            return true;
        }
    
        //时间复杂度O(n)
        //空间复杂度O(n)
    一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
  • 相关阅读:
    vue 跳转路由传参数用法
    百度地图放大之后,多边形,矩形覆盖物消失
    百度地图画多边形,画圆, 监听事件不触发原因
    兄弟组件之间如何通信
    vue如何触发某个元素的单击事件?
    input 清空值。(转载)
    inline-block元素水平居中问题
    android 浏览器对图片加载高度渲染问题
    IE下png图片黑边问题
    IE css hack整理
  • 原文地址:https://www.cnblogs.com/fengtingxin/p/14248617.html
Copyright © 2011-2022 走看看