zoukankan      html  css  js  c++  java
  • LeetCode100-相同的树

    题目描述

    给定两个二叉树,编写一个函数来检验它们是否相同。
    如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

    递归同步判断

    我们常用递归遍历树,这里要求树的结构、节点值一样,我们可以同步遍历两棵树,即遍历时保持节点对应,并判断。
    实现:

     public boolean isSameTree(TreeNode p, TreeNode q) {
            if(q==null&&p==null)return true;//都为null,返回true
            if(p==null||q==null)return false;//只有一个为true,返回false
            return q.val==p.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);//返回节点值和左右递归结果
        }
    

    迭代解法

    适合用递归解决的,很多也可以用迭代方式解决,只不过或是要借助其他数据结构,或是编码复杂。
    前面写过树的层序遍历,这里可以借用。
    基本思路是:

    通过队列,按层次序遍历顺序,把节点放到队列中,逐对比较。
    这里又可以采用一个队列:一对一对的存取
    也可以采用两个队列:一个树用一个。

    不想实现了,贴一下人家的代码:

    public boolean isSameTree(TreeNode p, TreeNode q) {
            Queue<TreeNode> queue1 = new LinkedList<>();//这里就利用了2个队列
            Queue<TreeNode> queue2 = new LinkedList<>();
            queue1.add(q);
            queue2.add(p);
            while (!queue1.isEmpty()){
                TreeNode tempQ = queue1.remove();
                TreeNode tempP = queue2.remove();
                if (tempQ == null && tempP == null) continue;
                if (tempQ == null || tempP == null) return false;
                if(tempP.val != tempQ.val) return false;
                queue1.add(tempQ.left);
                queue1.add(tempQ.right);
                queue2.add(tempP.left);
                queue2.add(tempP.right);
            }
            return true;
        }
    //作者:ustcyyw
    
  • 相关阅读:
    html语法
    mysql常见的使用语法
    文件相关命令
    linux文件管理
    mysql常见名词解释
    MySQL初识
    文件管理
    并发基础知识3
    Bash shell初识
    【Spring Boot】ActiveMQ 发布/订阅消息模式介绍
  • 原文地址:https://www.cnblogs.com/XT-xutao/p/12885894.html
Copyright © 2011-2022 走看看