C++二叉树结构的建立与基本操作

这篇博客展示了如何使用C++实现二叉树的创建、清空、计数、打印、查找节点、查找叶子节点、遍历和计算深度等基本操作。通过示例代码详细解释了每个操作的过程。
摘要由CSDN通过智能技术生成

// Binary_tree.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

typedef int ElemType;
//typedef char ElemType;

typedef struct TreeNode_s
{
    ElemType Data;
    struct TreeNode_s *pLeft;
    struct TreeNode_s *pRight;
}*Ptree,Btree;

//二叉树的创建
Btree * CreateBiTree(Btree *root, ElemType data)
//void  CreateBiTree(Btree *root, ElemType data)
{

    Btree* pNewNode = NULL;

    pNewNode = new Btree;
    pNewNode->Data = data;
    pNewNode->pLeft = NULL;
    pNewNode->pRight = NULL;
    if (root == NULL)
    {
        root = pNewNode;
        return root;
    }
    else
    {
        Btree* pBackNode = NULL;
        Btree* pCurrentNode = root;
        while(pCurrentNode != NULL)
        {
            pBackNode = pCurrentNode;
            //cout << pCurrentNode->Data<<endl;
            if(pCurrentNode->Data > data) //查找左子树
            {
                pCurrentNode = pCurrentNode->pLeft;
            }
            else if (pCurrentNode->Data < data) //查找右子树
            {
                pCurrentNode = pCurrentNode->pRight;
            }
            else
            {
                delete pNewNode;
                return pCurrentNode;
            }
        }

        //cout << pBackNode->Data<<endl;
        //比较插入数据与当前叶子节点,如果大于插入左子树,否则插入右子树
        if (pBackNode->Data > data)
        {

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值