完全二叉树 链式 非递归 插入建树

最近遇到了一个需要使用非递归链式完全二叉树的情况。图中某个节点用这样的二叉树来储存多个相同特征的节点。
在网上粗略的找了一下没有看到,在这里先备份一下。
方法是在树的结构体中储存指向最后一个节点的指针lastLeaf和指向将要插入的位置的父亲的指针lastRt。
点的结构体中储存指向树中同层的下一节点next(或者下一行的第一个节点)。
在这里插入图片描述

#include<iostream>
#include<queue>
#define N 100
using namespace std;
struct Node{
	Node*left, *right;
	Node*next; //该点同层的下一节点或者当该点处于同层最后一个时,指向下一层第一个节点
	int data;
	Node(){ left = right = next = NULL; }
};
Node*par[N];
struct Tree{
	int size;
	Node*root;
	Node*lastRt;  //指向将要插入位置的父亲的指针
	Node*lastLeaf;  //指向最后一个节点的指针
	Tree(){ root = NULL; lastRt = lastLeaf = NULL; size = 0; }
	~Tree(){
		queue<Node*>q;
		q.push(root);
		while (!q.empty()){
			Node*rt = q.front(); q.pop();
			if (rt == NULL)return;
			q.push(rt->left);
			q.push(rt->right);
			delete rt;
		}
	}
	void insert(int x){
		par[x] = root;
		if (root == NULL){
			root = new Node;
			root->data = x;
			lastRt = root;
			lastRt->next = NULL;
			lastLeaf = root;
			size++;
			return;
		}
		if (lastRt->left == NULL){
			lastRt->left = new Node;
			lastRt->left->data = x;
			lastLeaf->next = lastRt->left;
			lastLeaf = lastLeaf->next;
			size++;
		}
		else if (lastRt->right == NULL){
			lastRt->right = new Node;
			lastRt->right->data = x;
			lastLeaf->next = lastRt->right;
			lastLeaf = lastLeaf->next;
			size++;
		}
		else{
			lastRt = lastRt->next;
			insert(x);
		}
	}
	void show(){
		queue<Node*>q;
		q.push(root);
		while (!q.empty()){
			Node*t = q.front(); q.pop();
			if (t == NULL)return;
			cout << t->data << " ";
			q.push(t->left);
			q.push(t->right);
		}
	}
	void preshow(Node*rt){
		if (rt == NULL)return;
		cout << rt->data << " ";
		preshow(rt->left);
		preshow(rt->right);
	}
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值