码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-05-24 08:57:31      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

bubuko.com,布布扣
#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);
}
bubuko.com,布布扣

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

用递归方法判断两棵树是否相等,布布扣,bubuko.com

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

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/berkeleysong/p/3747377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!