BinaryTree.h
//
// BinaryTree.hpp
// FirstP
//
// Created by 赫赫 on 2023/11/1.
//
#ifndef BinaryTree_hpp
#define BinaryTree_hpp
#define MaxSize 100
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
#include "Queue.hpp"
#endif /* BinaryTree_hpp */
//二叉树顺序存储,按照完全二叉树的方式来做,方便父子的对应
typedef struct{
int value;
bool empty;
}TreeNode;
//TreeNode t[MaxSize];来定义一个完全二叉树
//二叉树链式存储
typedef struct BiTNode{
int value;//数据域
struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;
//初始化树根节点
void initRoot(BiTree &tree,int value);
//递归实现二叉树的遍历
//访问节点数据
void visitNode(BiTNode *node);
//二叉树先序遍历
void PreOrder(BiTree T);
//二叉树中序遍历
void InOrder(BiTree T);
//二叉树后序遍历
void PostOrder(BiTree T);
//二叉树层序遍历
void LevelOrder(BiTree T);
//求树的高度(深度)
int treeDepth(BiTree T);
//-------------------临时链队操作
//入队操作
bool EnLinkQueue(LinkQueue &Q,int elem);
//出队操作
bool DeLinkQueue(LinkQueue &Q,int &elem);
//---------------------------
//线索二叉树结点定义
typedef struct ThreadNode{
int data;
struct ThreadNode *lchild,*rchild;//左孩子结点,右孩子结点
int lflag,rflag;//线索标志位
}TreadNode,*TreadTree;
BinaryTree.cpp
//
// BinaryTree.cpp
// FirstP
//
// Created by 赫赫 on 2023/11/1.
// 二叉树相关代码:创建、遍历(深度、广度优先)
#include "BinaryTree.hpp"
//初始化树根节点
void initRoot(BiTree &tree,int value){
tree=(BiTNode*)malloc(sizeof(BiTNode));
tree->value=value;
tree->lchild=NULL;
tree->rchild=NULL;
}
//递归实现二叉树的遍历
//访问节点数据
void visitNode(BiTNode *node){
cout<< node->value <<endl;
}
//二叉树先序遍历
void PreOrder(BiTree T){
if(T!=NULL){
visitNode(T);
PreOrder(T->lchild);//递归遍历左孩子
PreOrder(T->rchild);//递归遍历右孩子
}
}
//二叉树中序遍历
void InOrder(BiTree T){
if(T!=NULL){
InOrder(T->lchild);//递归遍历左孩子
visitNode(T);
InOrder(T->rchild);//递归遍历右孩子
}
}
//二叉树后序遍历
void PostOrder(BiTree T){
if(T!=NULL){
PostOrder(T->lchild);//递归遍历左孩子
PostOrder(T->rchild);//递归遍历右孩子
visitNode(T);
}
}
//-----------------------临时的队列操作
//入队操作
bool EnLinkQueue(LinkQueue &Q,BiTree &T){
return true;
}
//出队操作
bool DeLinkQueue(LinkQueue &Q,BiTree &T){
return true;
}
//判断队列是否为空
bool IsEmpty(LinkQueue &Q){
return false;
}
//-----------------------
//二叉树层序遍历
void LevelOrder(BiTree T){
LinkQueue Q;
InitLinkQueue(Q);
BiTNode *p;
EnLinkQueue(Q, T);//根结点先入队列
while(!IsEmpty(Q)){
DeLinkQueue(Q,p);
visitNode(p);//读取当前弹出的结点内容
if(p->lchild!=NULL){//当前结点左孩子不为空,压入队列
EnLinkQueue(Q, p->lchild);
}
if(p->rchild!=NULL){//当前结点右孩子不为空,压入队列
EnLinkQueue(Q, p->rchild);
}
}
}
//求树的高度(深度)
int treeDepth(BiTree T){
if(T==NULL){
return 0;
}else{
int ld=treeDepth(T->lchild);
int rd=treeDepth(T->rchild);
int depth=(ld>rd?ld+1:rd+1);
return depth;
}
}