c++ 树集合实现记录

本文探讨了C++中如何实现二叉树结构,包括基本的二叉搜索树、平衡AVL树以及堆的数据结构。
摘要由CSDN通过智能技术生成
  • 二叉树
#include<iostream>
#include<stack>
#include<queue>
using namespace std;

template<class Elem>
struct BinNode//定义二叉树链表
{
   
    Elem data;
    BinNode <Elem>* left;
    BinNode <Elem>* right;
    int h;
    BinNode(Elem x) {
   
        //初始化
        data = x;
        h = -1;
        left = right = NULL;
    }
};

//定义某种类的模板类型复杂数据时需要用 类名<..> 来声明类型
template<class Elem>
class BinTree {
   
protected:
    BinNode<Elem>* root;
    void rpreprint(BinNode<Elem>* r) {
   
        //递归遍历
        if (r == NULL) return;
        cout << r->data << " ";
        rpreprint(r->left);
        rpreprint(r->right);
    }
    BinNode<Elem>* rfindx(Elem x, BinNode<Elem>* r) {
   
        //树为空树,或者没找到
        if (!r) return NULL;
        //刚好找到了
        if (r->data == x) return r;
        //遍历查找
        BinNode<Elem>* found;
        found = rfindx(x, r->left);
        //不在左边,就在右边或者不存在
        // .....? x:y 三元表达式
        return found ? found : rfindx(x, r->right);
    }
    void rprint(BinNode<Elem>* r, int depth) {
   
        for (int i = 0; i < depth; i++) {
   
            cout << "  ";//深度越大,打印的空格越多
        }
        if (!r) {
   
            cout << "[/]" << endl;
        }
        else
        {
   
            cout << r->data << endl;
            rprint(r->left, depth + 1);//先打印左
            rprint(r->right, depth + 1);//后打印右
        }
    }

    void rinprint(BinNode<Elem>* r) {
   
        //递归遍历
        if (r == NULL) return;
        rpreprint(r->left);
        cout << r->data << " ";
        rpreprint(r->right);
    }

    void rbackprint(BinNode<Elem>* r) {
   
        //递归遍历
        if (r == NULL) return;
        rpreprint(r->left);
        rpreprint(r->right);
        cout << r->data << " ";
    }

    void ipreprint(BinNode<Elem>* r) {
   
        //用stack是为了记录路径
        stack<BinNode<Elem>*> st;
        if (!r) return;
        while (r)
        {
   
            cout << r->data << ' ';
            st.push(r);
            r = r->left;
            while (r == NULL && !st.empty()) {
   
                r = st.top();
                st.pop();
                r = r->right;
            }
        }
    }

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值