博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
两棵树是否相同
阅读量:7072 次
发布时间:2019-06-28

本文共 889 字,大约阅读时间需要 2 分钟。

hot3.png

原题

  Given two binary trees, write a function to check if they are equal or not.

  Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

题目大意

  给定两个二叉树,判断这两棵树是否相等。

  仅当两棵树的结构相同,结点值都相等时都会相等。

解题思路

  使用递归进行求解,先判断当前结点值是否相等,如果相等就再比较其左右子树,只有当所有的结点都相等才相等。

代码实现

树结点类

public class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x) { val = x; }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

实现类

public class Solution {    public boolean isSameTree(TreeNode p, TreeNode q) {        if (p == null && q == null ) {            return true;        }        if (p != null && q == null) {            return false;        }        if (p == null && q != null) {            return false;        }        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);    }}

转载于:https://my.oschina.net/u/2822116/blog/808769

你可能感兴趣的文章
spring学习笔记(五)
查看>>
linux 下 用mount 挂载 samba 以及Linux 开机自动挂载 samba
查看>>
常见HTTP状态(304,200等)
查看>>
如何在系统下获取Dell机器的服务编号
查看>>
linux下配置snmp服务
查看>>
mongo用户与权限
查看>>
PHP异常最简洁最直接的学习案例
查看>>
nmap入门之端口说明和扫描顺序
查看>>
我眼中的运维工作
查看>>
Java 内存管理和垃圾回收机制
查看>>
大家好,今天入住51CTO博客
查看>>
Bat 命令使用
查看>>
dmidecode 查看硬件详细信息
查看>>
elasticsearch 常用管理命令
查看>>
VMware vSphere 4.1虚拟化学习手册11:使用Converter工具V2V、P2V导入虚拟机
查看>>
我的友情链接
查看>>
python 正则表达式 笔记
查看>>
possible SYN flooding on port 80. Sending cookies
查看>>
联想天工ispirit 4505核心交换机配置笔记
查看>>
【CISCO技术】GRE-虚拟专用网络(静态)
查看>>