zoukankan      html  css  js  c++  java
  • 对称二叉树

    题目链接:

    涉及知识:二叉树

    定义结点的结构:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    

    分析:

    什么时候两颗二叉树是镜像对称的?

    • 两棵二叉树具有相同的根节点
    • 第一棵的左子树和第二棵右子树镜像对称,第二棵的左子树和第一棵右子树镜像对称

    1. 递归

    class Solution {
        public boolean isSymmetric(TreeNode root) {
            if(root == null){
                return true;
            } else {
                return isSymmetric(root.left, root.right);
            }
        }
    	
        //判断两棵二叉树是否镜像对称
        public boolean isSymmetric(TreeNode root1, TreeNode root2){
            if(root1 == null && null == root2){
                return true;
            } else if(root1 == null || root2 == null){      //一棵为空,一棵非空
                return false;
            } else {
                return root1.val == root2.val && isSymmetric(root1.left, root2.right) && isSymmetric(root1.right, root2.left);
            }
        }
    }
    

    2. 迭代

    将两棵二叉树的左右子树交叉以相反的顺序插入队列,每次从队列中取出两个节点,如果该二叉树是镜像对称的,那么每次取出的两个节点必定是相同的,否则,即说明该二叉树不是镜像对称的

    class Solution {
        public boolean isSymmetric(TreeNode root) {
            Queue<TreeNode> que = new LinkedList<>();
    
            que.offer(root);
            que.offer(root);
    
            while(!que.isEmpty()){
                TreeNode t1 = que.poll();
                TreeNode t2 = que.poll();
    
                if(t1 == null && null == t2){
                    continue;
                }
                if(t1 == null || null == t2){
                    return false;
                }
                if(t1.val != t2.val){
                    return false;
                }
                que.offer(t1.left);
                que.offer(t2.right);
                que.offer(t2.left);
                que.offer(t1.right);
            }
    
            return true;
        }
    }
    
  • 相关阅读:
    Django之模板
    Django之视图
    Django之web框架和url路由
    SpringBoot整合Druid数据源
    SpringBoot整合定时任务异步任务
    逐行解读HashMap源码
    SpringBoot通过RedisTemplate执行Lua脚本
    SpringBoot使用H2内嵌数据库
    SpringBoot如何使用拦截器
    SpringBoot热部署的实现方式
  • 原文地址:https://www.cnblogs.com/zcxhaha/p/11329185.html
Copyright © 2011-2022 走看看