#include<iostream>
#include<stack>
#include<queue>
using namespace std;
/*class link{
public:
int data;
link* next;
link(int d):data(d),next(NULL){}
link *head;
link* tail;
};
class stack{
public:
link *top;
int size;
stack(int sz):top(NULL),size(sz){}
stack():top(NULL),size(0){}
~stack(){
clear();
}
void clear(){
while(top!=NULL){
link * temp = top;
delete temp;
top = top->next;
}
size = 0;
}
void push(int it){
if(top==NULL){
top = new link(it);
size++;
}else{
link * temp = new link(it); //把新加入的值放进temp中
temp->next = top; //让TEMP指向top,和stack连起来
top = temp; //此时的temp变成了top
}
}
bool empty(){
if(top==NULL)
return true;
else
return false;
}
void pop(){
link *temp = top;
delete temp;
top = top->next;
size--;
}
};
*/
class BinTree{
public:
int data;
BinTree* left;
BinTree* right;
BinTree(int d):data(d),left(NULL),right(NULL){}
BinTree* root;
BinTree():root(NULL){}
BinTree* createBintree(){
BinTree* T = new BinTree;
char ch;
cin>>ch;
if(ch=='#'){
T = NULL;
}else{
T->data = ch; //初始化当前结点
T->left = createBintree(); //递归构造左子树
T->right = createBintree(); //递归构造右子树
}
return T;
}
void preorder(BinTree* T){
if(T==NULL){
return;
}else{
cout<<T->data; //访问根节点
T->preorder(T->left);
T->preorder(T->right);
}
}
//非递归的前序遍历
void preorder2(BinTree* T){
stack<BinTree*> s;
BinTree* temp = T;
while(temp||!s.empty()){
cout<<temp->data<<" "; //打印当前结点
s.push(temp); //当前结点入栈
temp = temp->left; //访问左子树
while(temp==NULL&&!s.empty()){
temp = s.top(); //栈内最后一个保存为当前结点
s.pop(); //pop一个出来
temp = temp->right; //访问右子树
}
}
}
void print(BinTree* T){
//层次遍历
queue<BinTree*> q; //用于移动
BinTree* cur = T;
q.push(cur); //头结点入队
//队列为空时循环结束
while(!q.empty()){
//队列头元素出队
cur = q.front();
q.pop();
cout<<cur->data;
//左孩子不为空入队
if(cur->left!=NULL){
q.push(cur);
}
//右孩子不为空时入队
if(cur->right!=NULL){
q.push(cur);
}
}
}
int height(BinTree* T){
if(T){
//递归求左右子树高度
int lheight = height(T->left);
int rheight = height(T->right);
//树的高度等于左右子树中高的那个+1(因为有root)
int height = (lheight>rheight)?lheight:rheight;
height++;
return height;
}
return 0;
}
};
二叉树构造与遍历
最新推荐文章于 2022-05-24 22:28:15 发布