【数据结构】C++实现二叉树的基本操作:创建、遍历、查找、高度计算与销毁

C++实现二叉树的基本操作:创建、遍历、查找、高度计算与销毁

二叉树的基本操作,包括:

  • 二叉树的创建(基于括号表示法)
  • 二叉树的遍历(结构打印)
  • 节点查找
  • 计算树的高度
  • 二叉树的销毁

本文代码可作为初学者了解和掌握树结构基本操作的一个参考模板。


一、二叉树结构定义

typedef char ElemType;
typedef struct node {
    ElemType data;
    struct node *lchild;
    struct node *rchild;
} BTNode;

二叉树的每个节点包含一个数据域和两个指针域,分别指向左子树和右子树。


二、根据括号表示法创建二叉树

void CreateBTree(BTNode *&b, string str)

此函数接收一个类似 "A(B(D(,G)),C(E,M))" 的字符串,按照括号表示法来构建整棵树。

关键思路:

  • 使用栈模拟树的构建过程;
  • 遇到 ( 入栈,准备连接左子树;
  • 遇到 , 表示即将连接右子树;
  • 遇到 ) 弹栈回退;
  • 其他字符则创建新节点并连接到当前栈顶。

三、打印二叉树结构

void DispBTree(BTNode *b)

此函数通过递归方式将二叉树结构按括号格式输出,能够直观展示树的结构:

输出示例:

A(B(D(,G)),C(E,M))

四、查找指定节点

BTNode *FindNode(BTNode *b, ElemType x)

此函数采用先序遍历思想递归查找指定元素 x,若找到返回对应节点指针,未找到返回空指针。

例如查找 F,结果如下:

b中不存在F结点

五、计算二叉树的高度

int BTHeight(BTNode *b)

该函数采用自底向上的递归思路,计算左右子树的高度,最终返回树的最大高度:

return (lhigh > rhigh) ? (lhigh + 1) : (rhigh + 1);

输出结果:

树的高度为:4

六、销毁二叉树

void DestoryBTree(BTNode *b)

为了防止内存泄漏,使用后序遍历删除所有节点,释放动态分配的内存空间。


七、完整测试代码与运行结果

主函数中完成创建、遍历、查找和高度测试:

int main()
{
    BTNode *b, *p;
    string s = "A(B(D(,G)),C(E,M))";
    CreateBTree(b, s);
    printf("b: ");
    DispBTree(b);
    cout << "\n";

    p = FindNode(b, 'F');
    if (p != NULL)
        cout << "b中存在F结点\n";
    else
        cout << "b中不存在F结点\n";

    int h = BTHeight(b);
    cout << "树的高度为:" << h << endl;

    DestoryBTree(b);
    return 0;
}

运行结果示例:

b: A(B(D(,G)),C(E,M))
b中不存在F结点
树的高度为:4

八、完整code

// 二叉树的基本用法
#include 
#include 
using namespace std;
#define MaxSize 100
typedef char ElemType;
typedef struct node
{
    ElemType data;
    struct node *lchild;
    struct node *rchild;
} BTNode;

// 创建二叉树
void CreateBTree(BTNode *&b, string str)
{
    BTNode *St[MaxSize], *p = nullptr;
    int top = -1, k, j = 0; // k == 1 表示当前准备插入的是左子树,k == 2 表示右子树
    char ch;
    b = nullptr; // 建立的二叉树初始为空
    ch = str[j];
    while (ch != '\0')
    {
        switch (ch)
        {
        case '(':
            St[++top] = p;
            k = 1;
            break;
        case ')':
            top--;
            break;
        case ',':
            k = 2;
            break;
        default:
            p = new BTNode();
            p->data = ch;
            p->lchild = p->rchild = nullptr;
            if (b == nullptr)
                b = p; // *p 为二叉树的根节点
            else
            {
                switch (k)
                {
                case 1:
                    St[top]->lchild = p;
                    break;
                case 2:
                    St[top]->rchild = p;
                    break;
                }
            }
        }
        j++;
        ch = str[j];
    }
}

// 打印二叉树
void DispBTree(BTNode *b)
{
    if (b != nullptr)
    {
        cout << b->data;
        if (b->lchild != nullptr || b->rchild != nullptr)
        {
            cout << "(";
            DispBTree(b->lchild);
            if (b->rchild != nullptr) // 有有孩子才需要打印逗号
                cout << ",";
            DispBTree(b->rchild);
            cout << ")";
        }
    }
}

// 二叉树的摧毁
void DestoryBTree(BTNode *b)
{
    if (b != nullptr)
    {
        DestoryBTree(b->lchild);
        DestoryBTree(b->rchild);
        delete (b);
    }
}


// 查找节点
BTNode *FindNode(BTNode *b, ElemType x)
{
    BTNode *p;
    if (b == nullptr)
        return nullptr;
    else if (b -> data == x) return b;
    else
    {
        // 先找左子树
        p = FindNode(b->lchild, x);
        if (p != nullptr)
            return p;
        else    
            return FindNode(b->rchild, x);
    }
}

// 求树的高度
int BTHeight(BTNode *b)
{
    int lhigh, rhigh;
    if (b == nullptr)
        return 0;
    else
    {
        lhigh = BTHeight(b->lchild);
        rhigh = BTHeight(b->rchild);
        return (lhigh > rhigh) ? (lhigh + 1) : (rhigh + 1);
    }
}


int main()
{
    BTNode *b, *p;
    string s = "A(B(D(,G)),C(E,M))";
    CreateBTree(b, s);
    printf("b: ");
    DispBTree(b);
    cout << "\n";
    p = FindNode(b, 'F');
    if (p != NULL)
        cout << "b中存在F结点\n";
    else
        cout << "b中不存在F结点\n";
    int h = BTHeight(b);
    cout << "树的高度为:" << h << endl;
    DestoryBTree(b);
    return 0;
}

你可能感兴趣的:(数据结构,c++,开发语言)