+ -
当前位置:首页 → 问答吧 → 关于按值查找二叉树结点,求帮助.....谢谢!

关于按值查找二叉树结点,求帮助.....谢谢!

时间:2011-10-30

来源:互联网

我是想按值查找二叉树中的结点,就是输入x,在二叉树中若找到x,则输出x和其孩子;没找到,输出没没找到。
但是我写的代码不知道哪里出错了,实现不了我要的结果。
  希望大家路过,帮帮我,非常感谢!
  下面是我写的代码:

[code=C/C++][/code]
#include <iostream>
using namespace std;
typedef char datatype;
typedef struct node *pointer;
struct node 
{
datatype data;
pointer lchild,rchild;
};
typedef pointer bitree;

bitree PreCreat() //先根序列建立二叉树
{
bitree t;
char ch;
cin>>ch;
if(ch=='@') return NULL;
t=new node;
t->data=ch;
t->lchild=PreCreat();
t->rchild=PreCreat();
return t;
}

pointer Search(bitree t, datatype x) //在二叉树中查询值为x的节点
{
if(t==NULL) return NULL;  
if(t->data==x) return t; 
Search(t->lchild,x);
Search(t->rchild,x);
}

int main()
{
bitree t;
pointer p;
datatype x;
cout<<"先根建立二叉树,用@表示虚结点:";
t=PreCreat();

cout<<"输入要查找的值:";
cin>>x;
p=Search(t,x);
if(p!=NULL) //输出x结点的孩子
{
if(t->lchild==NULL && t->rchild!=NULL)  
cout<<"找到值为"<<x<<"的结点"<<",其右孩子为:"<<t->rchild->data<<",没有左孩子。"<<endl;
else if(t->lchild!=NULL && t->rchild==NULL)
cout<<"找到值为"<<x<<"的结点"<<",其左孩子为:"<<t->rchild->data<<",没有右孩子。"<<endl;
else if(t->lchild!=NULL && t->rchild!=NULL)
cout<<"找到值为"<<x<<"的结点"<<",其左孩子为:"<<t->lchild->data<<",右孩子为:"<<t->rchild->data<<endl;
else  
cout<<"找到值为"<<x<<"的结点,"<<"它没有孩子。"<<endl;
}
else cout<<"二叉树中没有"<<x<<"结点"<<endl;

return 0;
}

作者: xiaoou33   发布时间: 2011-10-30

C/C++ code
#include <iostream>
using namespace std;
typedef char datatype;
typedef struct node *pointer;
struct node  
{
    datatype data;
    pointer lchild,rchild;
};
typedef pointer bitree;

bitree PreCreat() //先根序列建立二叉树
{
    bitree t;
    char ch;
    cin>>ch;
    if(ch=='@') return NULL;
    t=new node;
    t->data=ch;
    t->lchild=PreCreat();
    t->rchild=PreCreat();
    return t;
}
// 保证所有路径都有返回值。。。
pointer Search(bitree t, datatype x) //在二叉树中查询值为x的节点
{
    if(t->data==x) 
        return t; 
    else if (t->lchild)
        return Search(t->lchild,x);
    else if (t->rchild)
        return Search(t->rchild,x);

    return NULL;
}

void Print(pointer t)
{
    if (t)
    {
        cout << t->data << " ";
        Print(t->lchild);
        Print(t->rchild);
    }
}

int main()
{
    bitree t;
    pointer p;
    datatype x;
    cout<<"先根建立二叉树,用@表示虚结点:";
    t=PreCreat();

    cout<<"输入要查找的值:";
    cin>>x;
    p=Search(t,x);
    Print(p);

    system("PAUSE");

    return 0;
}

作者: dizuo   发布时间: 2011-10-30

热门下载

更多