等价二叉树
来源:互联网 发布:淘宝数码相机 编辑:程序博客网 时间:2024/06/15 04:40
问题描述:
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
1 1 / \ / \ 2 2 and 2 2 / /4 4
就是两棵等价的二叉树。
1 1 / \ / \ 2 3 and 2 3 / \4
4
就不是等价的。
解题思路:
首先判断两个二叉树是否有相同的结构。当两个二叉树都为空时,返回1,;若其中一个为空另一个不为空,则返回0。对左子树和右子树做相同的判断。然后判断相同位置的数值是否相等。
代码实现:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
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) {
// Write your code here
if(a==NULL&&b==NULL) return 1;
if((a==NULL&&b!=NULL)||(a!=NULL&&b==NULL)) return 0;
if(a->val==b->val)
return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right);
else return 0;
}
};
解题感悟:
当所有相同位置的数值相同时才可返回1,第一次做的时候,只要某一位置的数值相同就返回1了,应该返回isIdentical(a->left,b->left)&&isIdentical(a->right,b->right),即每一个位置都要满足条件。
- LintCode_469_等价二叉树
- LintCode:等价二叉树
- lintcode ----等价二叉树
- 等价二叉树
- 等价二叉树-lintcode
- 等价二叉树,lintcode
- lintcode-->等价二叉树
- lintcode,等价二叉树
- 等价二叉树
- LintCode-等价二叉树
- 等价二叉树
- 等价二叉树
- 等价二叉树
- LIntCode 等价二叉树
- 等价二叉树
- 等价二叉树-LintCode
- 等价二叉树
- 等价二叉树
- windows7下安装centos双系统
- Apache错误日志时时查看
- 实验5 运算符重载
- 实验6 继承
- 实验7 多态与模板
- 等价二叉树
- 排序算法之冒泡排序(Bubble Sort)
- c++ debugger package is missing or incompatible,无法debug应用
- 指针 数组 变量名
- [置顶]教材配套PPT初稿
- 类与对象
- 最少拦截系统
- javaScript封装的各种写法
- 本地开发环境配置Nginx