Question

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.

Solution

递归判断,首先要判断结构是否一样,如果不一样直接返回false,如果结构一样,那么要继续判断值是否相等,如果不等直接返回false,如果相等,那么继续遍历左子树和右子树。

Code

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (p == NULL && q == NULL)
return true;
if (p == NULL)
return false;
if (q == NULL)
return false;
if (p->val == q->val) {
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
} else
return false;
}
};

最新文章

  1. Atitit.软件研发团队建设原理与概论 理论
  2. AVAudioPlayer
  3. 体育游戏中的Player类
  4. python走起之第十三话
  5. Codeforces Round #282 Div.1 B Obsessive String --DP
  6. [转]Windows 8.1删除这台电脑中视频/文档/下载等六个文件夹的方法
  7. python3 字符串相关函数
  8. WIN7 X64 解决无法安装IE11,以及无法点击微软升级包MSU的问题
  9. 5个缺失的 JavaScript 数字格式化函数
  10. IMAQdx和IMAQ
  11. 18个有用的 .htaccess 文件使用技巧
  12. 速卖通api--发起授权
  13. ie8 hack
  14. C#基础之------控制台进程
  15. python向mysql中存储JSON及Nodejs取出
  16. [Python Study Notes]字典操作
  17. python实现四则运算和效能分析
  18. java.lang.ClassCastException: net.sf.json.JSONNull cannot be cast to net.sf.json.JSONObject的解决方法
  19. keras神经网络三个例子
  20. linux下安装SlickEdit

热门文章

  1. RTSP安防摄像机(海康大华宇视等)如何推送到RTMP流媒体服务器进行直播
  2. Hibernate 延迟加载的代理模式 和 Spring AOP的代理模式
  3. redis集群报错,(error) MOVED 15495 127.0.0.1:7003
  4. [NOIP2018PJ]对称二叉树
  5. Windows Server 2012 下安装MySQL 5.6 X64位包
  6. 0x05 MySQL 数据操作
  7. Python定时执行脚本
  8. 深度学习:Keras入门(一)之基础篇(转)
  9. 《Python数据分析》笔记2——统计学与线性代数
  10. vim tabs