编写程序,使用满二叉树编号方式建立二叉树(C++)

#pragma once

#define MAX_TREE_SIZE 100
// 指定树结点存储的数据类型
typedef char ElemType;

typedef struct PTNode {
	ElemType data;
	int parent;     // 双亲位置域     
} PTNode;
// 树结构
typedef struct {
	PTNode nodes[MAX_TREE_SIZE];
	int r, n;      // 根的位置和结点数          
}PTree;


typedef bool Status;
#define OK true;
#define ERROR false;

// 输入创建满二叉树
Status CreatePTree(PTree& T);
// 打印
void printPT(PTree& T);

文件tree.h

#define _CRT_SECURE_NO_DEPRECATE 
#include "tree.h"
#include <malloc.h>
#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;

// 输入创建满二叉树
Status CreatePTree(PTree& T) {
	char ch = 'A';
	if (T.n < 0) T.n = 0;
	// * 表示空
	while (ch != '*') {
		PTNode P;
		scanf("%c", &ch);
		P.data = ch;
		T.nodes[T.n++] = P;
	}
	int depth = 0;
	int all = T.n;
	int temp = 1;
	while (all > 0) {
		all -= temp;
		depth++;
		temp *= 2;
	}
	while (T.n < pow(2, depth) - 1) {
		PTNode P;
		P.data = '*';
		T.nodes[T.n++] = P;
	}
	return OK;
}

void printPT(PTree& T) {
	int len = T.n;
	while (len-- > 0) {
		cout << T.nodes[T.n - len - 1].data << ' ';
	}
}

文件tree.cpp

#include <stdio.h>
#include "tree2.h"
#include "tree.h"

int main() {
	PTree P;
	printf("满二叉输入\n");
	CreatePTree(P);
	printf("\n数组结构\n");
	printPT(P);
	return 0;
}

文件main.cpp

测试结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值