当前位置:C++技术网 > 资讯 > 二叉树实现查找和统计个数、比较、求深度的递归

二叉树实现查找和统计个数、比较、求深度的递归

更新时间:2015-10-30 23:29:57浏览次数:1+次

前面一章讲了二叉树的简单遍历

这次简单讲讲其他几个实现

二叉树的查找

bintree search_tree(bintree t,datatype x){
    if(!t){
        return NULL;
    }
    if(t->data == x){
        return t;
    }else{
        if(!search_tree(t->lchild,x)){
            return search_tree(t->rchild,x);
        }
        return t;
    }
}
统计结点个数
int count_tree(bintree t){
    if(t){
        return (count_tree(t->lchild)+count_tree(t->rchild)+1);
    }
    return 0;
}
比较两个树是否相同


int is_equal(bintree t1,bintree t2){
    if(!t1 && !t2){      //都为空就相等
        return 1;
    }
    if(t1 && t2 && t1->data == t2->data){      //有一个为空或数据不同就不判断了
        if(is_equal(t1->lchild,t2->lchild))
            if(is_equal(t1->rchild,t2->rchild)){
                return 1;
            }
    }
    return 0;
}
求二叉树的深度


int hight_tree(bintree t){
    int h,left,right;
    if(!t){
        return 0;
    }
    left = hight_tree(t->lchild);
    right = hight_tree(t->rchild);
    h = (left>right?left:right)+1;
    return h;
}


如有错误欢迎提出