最近遇到了一个需要使用非递归链式完全二叉树的情况。图中某个节点用这样的二叉树来储存多个相同特征的节点。
在网上粗略的找了一下没有看到,在这里先备份一下。
方法是在树的结构体中储存指向最后一个节点的指针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);
}
};