用递归方法判断两棵树是否相等

#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);
}

之前一直用非递归的方法,麻烦的要死,这真是一个好方法

posted on 2014-05-23 11:59  berkeleysong  阅读(626)  评论(0编辑  收藏  举报

导航