c++,二叉树

#include <iostream>

#include <algorithm>

#include <string>

#include <cmath>

#include <time.h>

using namespace std;

typedef struct Node {

int key,ltag,rtag;

Node *lchild,*rchild;

} Node;

Node *getNewNode(int key) {

Node *p=(Node*)malloc(sizeof(Node));

p->key=key;

p->ltag=p->rtag=0;

p->lchild=p->rchild=NULL;

return p;

}

Node *insert(Node *root,int key) {

if(!root)return getNewNode(key);

if(rand()%2)root->lchild=insert(root->lchild,key);

else root->rchild=insert(root->rchild,key);

return root;

}

void clear(Node *root) {

if(!root)return ;

clear(root->lchild);

clear(root->rchild);

free(root);

return ;

}

void pre_order(Node *root) {

if(!root)return ;

cout<<root->key<<" ";

if(!root->ltag)pre_order(root->lchild);

if(!root->rtag)pre_order(root->rchild);

return ;

}

void in_order(Node *root) {

if(!root)return ;

if(!root->ltag)in_order(root->lchild);

cout<<root->key<<" ";

if(!root->rtag)in_order(root->rchild);

return ;

}

void post_order(Node *root) {

if(!root)return ;

if(!root->ltag)post_order(root->lchild);

if(!root->rtag)post_order(root->rchild);

cout<<root->key<<" ";

return ;

}

Node *pre_node=NULL,*inorder_root=NULL;

void __build_inorder_thread(Node *root) {

if(!root)return ;

if(!root->ltag)__build_inorder_thread(root->lchild);

if(inorder_root==NULL)inorder_root=root;

if(root->lchild==NULL) {

root->lchild=pre_node;

root->ltag=1;

}

if(pre_node&&pre_node->rchild==NULL) {

pre_node->rchild=root;

pre_node->rtag=1;

}

pre_node=root;

if(!root->rtag)__build_inorder_thread(root->rchild);

return ;

}

void build_inorder_thread(Node *root) {

__build_inorder_thread(root);

pre_node->rchild=NULL;

pre_node->rtag=1;

return ;

}

Node *getNext(Node *root){

if(root->rtag==1)return root->rchild;

root=root->rchild;

while(root->ltag==0&&root->lchild)root=root->lchild;

return root;

}

int main() {

srand(time(0));

Node *root=NULL;

for(int i=0; i<10; i++) {

root=insert(root,rand()%100);

}

pre_node=inorder_root=NULL;

build_inorder_thread(root);

pre_order(root);

printf("\n");

in_order(root);

printf("\n");

post_order(root);

cout<<endl;

Node *node=inorder_root;

while(node) {

cout<<node->key<<" ";

node=getNext(node);

}

clear(root);

return 0;

}

相关推荐
GUIQU.2 分钟前
【每日一题 | 2025年5.5 ~ 5.11】搜索相关题
算法·每日一题·坚持
双叶8363 分钟前
(C语言)超市管理系统(测试版)(指针)(数据结构)(二进制文件读写)
c语言·开发语言·数据结构·c++
不知名小菜鸡.3 分钟前
记录算法笔记(2025.5.13)二叉树的最大深度
笔记·算法
真的想上岸啊32 分钟前
c语言第一个小游戏:贪吃蛇小游戏05
c语言·算法·链表
格林威40 分钟前
Baumer工业相机堡盟工业相机的工业视觉是否可以在室外可以做视觉检测项目
c++·人工智能·数码相机·计算机视觉·视觉检测
追烽少年x42 分钟前
C++11异步编程 --- async
c++
元亓亓亓1 小时前
LeetCode热题100--206.反转链表--简单
算法·leetcode·链表
诚丞成1 小时前
BFS算法篇——从晨曦到星辰,BFS算法在多源最短路径问题中的诗意航行(上)
java·算法·宽度优先
hongjianMa1 小时前
2024睿抗编程赛国赛-题解
算法·深度优先·图论·caip
czy87874752 小时前
两种常见的C语言实现64位无符号整数乘以64位无符号整数的实现方法
c语言·算法