非递归实现 二叉树 先序、后序、中序遍历

本文介绍了一种使用栈实现的二叉树遍历方法,包括先序遍历、中序遍历和后序遍历,并提供了完整的C++代码示例。通过递归和非递归的方式实现了树的遍历过程。

想想理所当然的认为容易,身体力行时则有些困难~

#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;
}

转载于:https://www.cnblogs.com/25-to-life/archive/2011/10/10/2205728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值