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;

}

相关推荐
Hello.Reader8 分钟前
迭代器介绍与使用(四十一)
开发语言·c++
手握风云-13 分钟前
优选算法的妙思之流:分治——归并专题
数据结构·算法·排序算法
梭七y27 分钟前
【力扣hot100题】(063)搜索二维矩阵
算法·leetcode·职场和发展
哦吼!1 小时前
算法基础-枚举
算法
重生之我要成为代码大佬1 小时前
从零讲透DFS-深度优先搜索-2(排序与组合)
开发语言·python·算法·深度优先遍历
永不停转1 小时前
从源码解析 QGraphicsItem 旋转、缩放、平移、transform等变换操作,利用QGraphicsTransform实现变形动画
c++·qt
双叶8361 小时前
(51单片机)独立按键控制流水灯LED流向(独立按键教程)(LED使用教程)
c语言·开发语言·数据结构·单片机·嵌入式硬件·游戏·51单片机
uhakadotcom1 小时前
快速理解 tiktoken:OpenAI 模型的高效 BPE 分词器
算法·面试·github
鲸鱼宝宝成长记1 小时前
[蓝桥杯青少年组省赛 2024] 通关游戏的最少能量值
数据结构·算法
upward_growth1 小时前
一叶障目 -- 你不知道的"最长递增子序列"!
前端·javascript·算法