用递归方法判断两棵树是否相等
2014-05-23 11:59
260 查看
#include<iostream> #include<vector> #include<stack> #include<string> #include<queue> #include<algorithm> #include<numeric> using namespace std; class node{ public: int val; node* left; node* right; node():val(0),left(NULL),right(NULL){} }; node* createTree() { node* head = new node[14]; for(int i = 0;i<10;i++) { head[i].val = i; if(2*i+1 < 10) head[i].left = head + 2*i + 1; if(2*i+2 < 10) head[i].right = head + 2*i + 2; } return head; } bool isequal(node* t1,node* t2) { if(!t1 && !t2) return true; if((!t1&&t2)||(t1&&!t2)) return 0; if(t1->val == t2->val) { return isequal(t1->left,t2->left)&&isequal(t1->right,t2->right); }else return 0; } int main() { node* t1 = createTree(); node* t2 = createTree(); cout<<isequal(t1,t2); }
之前一直用非递归的方法,麻烦的要死,这真是一个好方法
相关文章推荐
- 用递归的方法判断一个数组是否为递增数组
- 判断两棵树是否相等
- 代码实现判断两棵树是否相等
- JavaScript中判断两个字符串是否相等的方法
- 重写equals方法判断类的值是否相等
- 判断两棵树是否相等
- Same Tree 判断两棵树是否相等
- 判断两棵树是否相等
- 判断两棵树是否相等 leecode
- JavaScript中判断两个字符串是否相等的方法
- 百度面试题:判断两棵树是否相等
- js判断两个日期是否相等的方法
- 判断两个(float)变量x,z是否相等 以及和0值比较方法
- php判断两个浮点数是否相等的方法
- java中判断类对象是否相等的方法
- 【每日面试题】使用递归方法判断数字是否是升序数组
- 递归方法判断数组是否为递增数组
- 用递归的方法,判断某个字符串是否为回文
- 判断两棵树是否相等
- php判断两个浮点数是否相等的方法