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

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

中英题面

  给定两个二叉树,写一个函数来检查它们是否相同。

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

  如果两棵树在结构上相同并且节点具有相同的值,则认为它们是相同的。

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

 

  示例 1:

  输入 :     1          1            / \       / \           2   3     2   3          [1,2,3],   [1,2,3]  输出: true

  Example 1:

  Input:     1         1            / \       / \           2   3     2   3          [1,2,3],   [1,2,3]  Output: true

  示例 2:

  输入  :    1          1            /           \           2             2            [1,2],     [1,null,2]  输出: false   Example 2:
  Input:     1         1            /           \           2             2          [1,2],     [1,null,2]  Output: false

  例 3:

  输入 :     1          1            / \       / \           2   1     1   2          [1,2,1],   [1,1,2]  输出: false

  Example 3:

  Input:     1         1            / \       / \           2   1     1   2          [1,2,1],   [1,1,2]  Output: false

 

 

  

算法
  递归判断,若当前结点都不为空且左右子树都相同或当前结点都为空时,则两棵当前子树相同,否则不同。
 
代码
1 # Definition for a binary tree node. 2 # class TreeNode: 3 #     def __init__(self, x): 4 #         self.val = x 5 #         self.left = None 6 #         self.right = None 7  8 class Solution: 9     def isSameTree(self, p, q):10         """11         :type p: TreeNode12         :type q: TreeNode13         :rtype: bool14         """15         if (p and q):16             return p.val == q.val and Solution.isSameTree(self, p.left, q.left) and Solution.isSameTree(self, p.right, q.right)17         elif (p or q):18             return False19         return True

转载于:https://www.cnblogs.com/Efve/p/8723347.html

你可能感兴趣的文章
纯js实现图片上传
查看>>
嵌入式SQL
查看>>
HDOJ(HDU) 2133 What day is it(认识下Java的Calendar类---日期类)
查看>>
甲级1002 A+B for Polynomials (25)
查看>>
centos部署flask
查看>>
hdu 4507 吉哥系列故事——恨7不成妻
查看>>
C与C++ 无参函数的区别
查看>>
WPF DesiredSize & RenderSize
查看>>
快速开发第一个SpringBoot应用
查看>>
表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列
查看>>
HTML video标签 兼容总结
查看>>
锡瓦塔内霍 墨西哥 / 巴克斯顿 /
查看>>
css+html应用实例1:滑动门技术的简单实现
查看>>
C++智能指针 auto_ptr
查看>>
Direct3D 索引缓存
查看>>
Eclipse开发环境的配置
查看>>
Java集合框架的学习
查看>>
elasticsearch结构化查询过滤语句-----4
查看>>
P4783 【模板】矩阵求逆
查看>>
Bootstrap 警告框(Alert)插件
查看>>