等价二叉树
来源:互联网 发布:学生宿舍网络设计方案 编辑:程序博客网 时间:2024/06/06 10:01
一、问题描述
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
1 1 / \ / \ 2 2 and 2 2 / /4 4
就是两棵等价的二叉树。
1 1 / \ / \ 2 3 and 2 3 / \4 4
就不是等价的。
运用递归算法,比较两棵树相同位置的节点,若相同,返回1,若不相等,返回0。
三、我的代码
class Solution {
public:
/**
* @aaram a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
bool isIdentical(TreeNode* a, TreeNode* b) {
if(a==NULL&&b==NULL) return 1;
if(a==NULL&&b!=NULL) return 0;
if(a!=NULL&&b==NULL) return 0;
if(a->val!=b->val) return 0;
bool left=isIdentical(a->left,b->left);
bool right=isIdentical(a->right,b->right);
return left&&right;
}
};
四、我的感想
问题的思想很简单,但是要注意分两棵树为不为空的情况,然后运用了bool型函数,返回0,1即可。
0 0
- LintCode_469_等价二叉树
- LintCode:等价二叉树
- lintcode ----等价二叉树
- 等价二叉树
- 等价二叉树-lintcode
- 等价二叉树,lintcode
- lintcode-->等价二叉树
- lintcode,等价二叉树
- 等价二叉树
- LintCode-等价二叉树
- 等价二叉树
- 等价二叉树
- 等价二叉树
- LIntCode 等价二叉树
- 等价二叉树
- 等价二叉树-LintCode
- 等价二叉树
- 等价二叉树
- 学习笔记- 自己写的关于生产者与消费者模式,还有定时任务的demo。
- hdu 1757(快速矩阵幂)
- java.lang.IllegalArgumentException: Illegal character in query at index ...解决办法
- 在Android Studio2.3.1上配置BufferKnife和Icepick
- 树莓派3--ffmpeg视频流传输--开源项目一(jsmpeg)
- 等价二叉树
- RIPv1基本配置
- Direct3D学习笔记(二)——精灵动画(Sprite)
- xdebug配合phpStorm调试
- MFC 问题汇总(02)(单实例启动)
- tf-idf相关
- oracle关于权限的一些sql语句
- centos7 创建桌面快捷方式
- Android开发之沉浸式状态栏