想想理所当然的认为容易,身体力行时则有些困难~
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define MAXSIZE 10000
#define SIZE 7
int preOder(int *tree){
int root = 1;
int stack[MAXSIZE];
int top = 0;
stack[top] = root;
top++;
int tnode = 0;
while(top != 0){
top--;
tnode = stack[top];
printf("%d ", tree[stack[top]]);
if(tnode*2+1< SIZE ){ //rigth
stack[top] = tnode*2+1;
top++;
}
if(tnode*2 < SIZE) { //left;
stack[top] = tnode*2;
top++;
}
}
}
int inOrder(int *tree){
int root = 1;
int stack[MAXSIZE];
int top = 0;
int tnode = 1;
while(true){
while( tnode < SIZE ){
stack[top++] = tnode;
tnode *= 2;
}
if(--top < 0 ) break;
tnode = stack[top];
cout << tree[tnode] << " " ;
tnode = tnode*2 + 1;
}
cout << endl;
}
int backOrder(int *tree){ //一个点要被访问到两次
int root = 1;
int stack[MAXSIZE];
int top = 0;
int vis[MAXSIZE];
int tnode = 1, flg = 0;
while(true){
while(tnode < SIZE && vis[tnode]!=1){
stack[top++] = tnode; vis[tnode] = 0;
tnode *= 2; //left
}
tnode = stack[--top];
if( vis[tnode] == 0) {
stack[top++] = tnode; vis[tnode] = 1;
tnode = tnode*2+1; //right
} else {
cout << tree[tnode] << " ";
}
if(top == 0 ) break;
}
cout << endl;
}
int tr(int i, int *x){
if(i*2<SIZE) tr(i*2, x);
cout << x[i] << " ";
if(i*2+1<SIZE) tr(i*2+1, x);
}
int main(){
int tree[] = {0, 1, 2, 3, 4, 5, 6};
tr(1, tree);
cout << endl;
inOrder(tree);
cout << "done" << endl;
}