zoukankan      html  css  js  c++  java
  • 剑指offer系列——58.对称的二叉树

    Q:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
    A:
    递归:

        bool isSymmetrical(TreeNode *pRoot) {
            if (!pRoot)
                return true;
            return comp(pRoot->left, pRoot->right);
        }
    
        bool comp(TreeNode *left, TreeNode *right) {
            if (left == nullptr)
                return right == nullptr;
            if (right == nullptr)
                return false;
            if(left->val!=right->val)
                return false;
            return comp(left->left, right->right) && comp(left->right, right->left);
        }
    

    非递归(感谢@hustZa):
    利用DFS:
    出栈的时候也是成对成对的 ,
    1.若都为空,继续;
    2.一个为空,返回false;
    3.不为空,比较当前值,值不等,返回false;
    4.确定入栈顺序,每次入栈都是成对成对的,如left.left, right.right ;left.rigth,right.left

     boolean isSymmetricalDFS(TreeNode pRoot)
        {
            if(pRoot == null) return true;
            Stack<TreeNode> s = new Stack<>();
            s.push(pRoot.left);
            s.push(pRoot.right);
            while(!s.empty()) {
                TreeNode right = s.pop();//成对取出
                TreeNode left = s.pop();
                if(left == null && right == null) continue;
                if(left == null || right == null) return false;
                if(left.val != right.val) return false;
                //成对插入
                s.push(left.left);
                s.push(right.right);
                s.push(left.right);
                s.push(right.left);
            }
            return true;
        }
    

    利用BFS:
    出队的时候也是成对成对的
    1.若都为空,继续;
    2.一个为空,返回false;
    3.不为空,比较当前值,值不等,返回false;
    4.确定入队顺序,每次入队都是成对成对的,如left.left, right.right ;left.rigth,right.left

     boolean isSymmetricalBFS(TreeNode pRoot)
        {
            if(pRoot == null) return true;
            Queue<TreeNode> s = new LinkedList<>();
            s.offer(pRoot.left);
            s.offer(pRoot.right);
            while(!s.isEmpty()) {
                TreeNode left= s.poll();//成对取出
                TreeNode right= s.poll();
                if(left == null && right == null) continue;
                if(left == null || right == null) return false;
                if(left.val != right.val) return false;
                //成对插入
                s.offer(left.left);
                s.offer(right.right);
                s.offer(left.right);
                s.offer(right.left);
            }
            return true;
        }
    
  • 相关阅读:
    IT开发者对Mac钟爱
    POJ 3486 &amp; HDU 1913 Computers(dp)
    基础排序算法
    LeetCode 70:Climbing Stairs
    Qt自己定义事件实现及子线程向主线程传送事件消息
    maven自己主动编译,解决你每次代码改动须要又一次编译的繁琐
    Unity定制 Image、Text的对象生成
    iOS学习4_UITableView的使用
    GTK+重拾--09 GTK+中的组件(一)
    Architecting Android…The clean way?
  • 原文地址:https://www.cnblogs.com/xym4869/p/12369071.html
Copyright © 2011-2022 走看看