二叉树的建立以及前序、中序、后序遍历的递归和非递归实现


#include <stdio.h>
#include <sys/types.h>
#include <iostream>
#include <stack>
using namespace std;

int src[]={2,3,4, -1,-1,5,-1,6,-1,-1,7, -1,-1};
int index=0;
typedef struct BinaryTreeNode
{
 int key;
 struct BinaryTreeNode* left;
 struct BinaryTreeNode* right;

}BinaryTreeNode,*BinaryTree;


BinaryTree createBinaryTree()
{
 BinaryTree Root;
 int x;
 x=src[index++];
 if (x==-1)
 {
  Root=NULL;
 }
 else
 {
  Root=(BinaryTree)malloc(sizeof(BinaryTreeNode));
  Root->key=x;
  Root->left=createBinaryTree();
  Root->right=createBinaryTree();
  
 }
 return Root;
}

void preOrderRecursive(BinaryTree  Root)
{
 if (Root)
 {
  cout<<Root->key<<endl;
  preOrderRecursive(Root->left);
  preOrderRecursive(Root->right);
 }
}

void preOrderIterate(BinaryTree Root)
{
 stack<BinaryTree> nodes;
 
 while(!nodes.empty()||Root!=NULL)
 {
  while(Root!=NULL)
  {
   cout<<Root->key<<endl;
   nodes.push(Root);
   Root=Root->left;
   
  }
  Root=nodes.top();
     nodes.pop();
  Root=Root->right;
 }
}


void InOrderRecursive(BinaryTree Root)
{
 if (Root)
 {
  InOrderRecursive(Root->left);
  cout<<Root->key<<endl;
  InOrderRecursive(Root->right);
 }

}

void InOrderIterate(BinaryTree Root)
{
 stack<BinaryTree> nodes;
 while(Root!=NULL||!nodes.empty())
 {
  while(Root!=NULL)
  {
   nodes.push(Root);
   Root=Root->left;
  }
  Root=nodes.top();
  cout<<Root->key<<endl;
  nodes.pop();
  Root=Root->right;
 }
}

void postOrderRecursive(BinaryTree Root)
{
 if (Root)
 {
  postOrderRecursive(Root->left);
  postOrderRecursive(Root->right);
  cout<<Root->key<<endl;
 }
}

void postOrderIterate(BinaryTree Root)
{

 BinaryTree cur=NULL;
 BinaryTree pre=NULL;
 stack<BinaryTree> nodes;
 if (Root==NULL)
 {
  return;
 }
 nodes.push(Root);
 while(!nodes.empty())
 {
  cur=nodes.top();
  if ((cur->left==NULL&&cur->right==NULL)||(pre!=NULL&&pre==cur->right))
  {
   cout<<cur->key<<endl;
   pre=cur;
   nodes.pop();
  }
  else
  {
   if (cur->right!=NULL)
   {
    nodes.push(cur->right);
   }
   if (cur->left!=NULL)
   {
    nodes.push(cur->left);
   }
  }
 }
}

void main()
{   

    BinaryTree Root=createBinaryTree();
 postOrderIterate(Root);
 printf("\n");
}

posted on 2013-09-07 16:59  lovelace86  阅读(241)  评论(0)    收藏  举报

导航