⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 新建 文本文档 (3).txt

📁 数据结构中求二叉树树高的VC实现
💻 TXT
字号:

你的问题还是一样的,
h没有定义成全局变量,所以得不到值,
第一,你可以把h改成全局量,或者
第二,把high(p,0)改成high(p,h),把void high(bnode *p,int h)
改成void high(bnode *p,int& h)
 

new_del
new_del  第2楼 回复于2004-8-15 11:21:00    
--------------------------------------------------------------------------------
 接受本回复作为正确回答


#include<stdio.h>
#include<malloc.h>
#define null 0
int counter=0;
int h,hl,hr;
typedef struct btreenode
{
    int data;
    struct btreenode  *lchild;
    struct btreenode  *rchild;
}bnode;

bnode  *create(int x,bnode *lbt,bnode *rbt)
{
    bnode *p;
    p=(bnode*)malloc(sizeof(bnode));
    p->data=x;
    p->lchild=lbt;
    p->rchild=rbt;
    return(p);
}
void ins_lchild(bnode *p,int x)
{
    bnode *q;
    if(p==null)
        printf("Illegal insert.");
    else
    {
        q=(bnode*)malloc(sizeof(bnode));
        q->data=x;
        q->lchild=null;
        q->rchild=null;
        p->lchild=q;
    }
}

void ins_rchild(bnode *p,int x)
{
    bnode *q;
    if(p==null)
        printf("Illegal insert");
    else
    {
        q=(bnode*)malloc(sizeof(bnode));
        q->data=x;
        q->lchild=null;
        q->rchild=null;
        p->rchild=q;
    }
}

int max(int a,int b)
{
    if(a>b)
        return(a);
    else
    {
        if(a<b)
            return(b);
        else
            return(a);
    }
}

void high(bnode *p,int &h)
{

    if(p==null)
        h=0;
    else
    {
        if(p->lchild!=null)
            high(p->lchild,hl);
        if(p->rchild!=null)
            high(p->rchild,hr);
        h=max(hl,hr)+1;
        
    }
    
}

void main()
{
    bnode *bt,*p,*q;
    int x;

    printf("Input root:");
    scanf("%d",&x);
    p=create(x,null,null);
    bt=p;
    scanf("%d",&x);
    while(x!=-1)
    {
        p=bt;
        q=p;
        while(x!=p->data&&q!=null)            
        {
            p=q;
            if(x<p->data)
                q=p->lchild;
            else
                q=p->rchild;
        }
        if(x==p->data)
        {
            printf("The number is always exit.");
        }        
        else
            if(x<p->data)
                ins_lchild(p,x);
            else
                ins_rchild(p,x);
        scanf("%d",&x);
    }
    p=bt;    
    high(p,h);
    printf("\n");    
    printf("h=%d\n",h); 
    
}
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -