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;

}

相关推荐
hjjdebug17 分钟前
ffplay6 播放器关键技术点分析 1/2
c++·ffmpeg·音视频
小小小新人121231 小时前
C语言 ATM (4)
c语言·开发语言·算法
Azxcc01 小时前
C++异步编程入门
开发语言·c++
吐泡泡_1 小时前
C++(STL源码刨析/vector)
c++
你的冰西瓜1 小时前
C++排序算法全解析(加强版)
c++·算法·排序算法
এ᭄画画的北北2 小时前
力扣-31.下一个排列
算法·leetcode
特立独行的猫a2 小时前
11款常用C++在线编译与运行平台推荐与对比
java·开发语言·c++
笑鸿的学习笔记2 小时前
qt-C++笔记之setCentralWidget的使用
c++·笔记·qt
绝无仅有2 小时前
企微审批对接错误与解决方案
后端·算法·架构