二叉树的算法实现

最近重新温习数据结构,自己编写了一个关于二叉树的代码,分享下。

#include<iostream>
#include<process.h>
using namespace std;

typedef struct TreeNode
{
    char c;
    TreeNode *leftchild;
    TreeNode *rightchild;
}TreeNode;

int cmpTree(TreeNode *tree1, TreeNode *tree2)
{
    bool isTree1_Null = (tree1 == NULL);
    bool isTree2_Null = (tree2 == NULL);
    if(isTree1_Null != isTree2_Null)
        return 0;
    if(isTree1_Null && isTree2_Null)
        return 1;
    if(tree1->c != tree2->c)
        return 0;
    return (cmpTree(tree1->leftchild, tree2->leftchild) & cmpTree(tree1->rightchild, tree2->rightchild)) | 
        (cmpTree(tree1->rightchild, tree2->leftchild) & cmpTree(tree1->leftchild, tree2->rightchild));
}

TreeNode *creat(int i)
{
    TreeNode *root;
    char c;
    if(i == 0)
        cout<<"Please input the element of root: ";
    else if(i == 1)
        cout<<"Please input the element of leftchild: ";
    else
        cout<<"Please input the element of rightchile: ";
    cin>>c;
    if(c == '#')
    {
        cout<<"Input stop"<<endl;
        return NULL;
    }
    else
    {
        if(!(root = (TreeNode *)malloc(sizeof(TreeNode))))
        {
            cout<<"Overflow"<<endl;
            exit(1);
        }
        root->c = c;
        root->leftchild = creat(1);
        root->rightchild = creat(2);
    }
    return root;
}

int main()
{
    TreeNode *tree1, *tree2;
    int i = 0;
    tree1 = creat(0);
    tree2 = creat(0);
    i = cmpTree(tree1, tree2);
    if(i == 1)
        cout<<"Equal"<<endl;
    else
        cout<<"Not equal"<<endl;
    return 0;
}

 

posted @ 2012-09-14 20:56  nuaa_zhou  阅读(215)  评论(0编辑  收藏  举报