二叉树基本操作C++实现

这篇博客介绍了如何使用C++实现二叉树的基本操作,包括先序遍历、中序遍历、创建二叉树、计算节点数量、度为2的节点数量、度为1的节点数量、叶子节点数量、树的高度以及判断是否为完全二叉树。通过示例代码展示了具体实现过程。

二叉树基本操作C++实现

基本操作预览:
先序遍历: element:1 element:2 element:3
中序遍历: element:2 element:1 element:3
二叉树的结点个数: 3
度为2的结点个数: 1
度为1的结点个数: 0
叶子结点个数: 2
二叉树的高度: 2
是不是完全二叉树(1-是;0-不是): 1

#include <stdio.h>

#include <iostream>


using namespace std;
typedef struct Node{
   
   
    int data;
    struct Node *lchild, *rchild;
}Node, *Tree;


void pre_order(Tree tree){
   
   
    
    cout << "element:" << tree->data << " " ;
    if (tree->lchild!=NULL) {
   
   
        pre_order(tree->lchild);
    }
    if (tree->rchild!=NULL) {
   
   
        pre_order(tree->rchild);
    }
   
}
// 中序遍历
void in_order(Tree tree){
   
   
    if (tree!=NULL) {
   
   
        in_order(tree->lchild);
        cout << "element:" << tree->data << " ";
        in_order(tree->rchild);
    }
    
}

// 创建二叉树
void create_tree(Tree &tree){
   
   
    int data = 0;

    cin >> data;
    
    if (data == -1) {
   
   
        tree = NULL;
    }else{
   
   
        tree = (Node *)malloc(sizeof(Node));
        tree->data = data;
        tree->lchild = NULL;
        tree->rchild = NULL;

        cout  << "结点:" << data << " 输入它的左结点, 若没有输入-1结束 " << endl;
        create_tree(tree->lchild);
        cout  << "结点:" << data << " 输入它的右结点, 若没有输入-1结束 " << 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值