二叉树的三种遍历相互推导

104 阅读1分钟
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

  struct TreeNode
  {
    struct TreeNode* left;
    struct TreeNode* right;
    char  elem;
 };

 void TreeAft(char inorder[], char preorder[], int length)
 {
   if(length == 0)
     {
       //cout<<"invalid length"<<endl;
       return;
     }
   TreeNode* node = new TreeNode;//Noice that [new] should be written out.
   node->elem = *preorder;
   int rootIndex = 0;
   while(rootIndex < length)
     {
       if(inorder[rootIndex] == *preorder)
       {
          break;
       }

       rootIndex++;
     }
   //Left
   TreeAft(inorder, preorder +1, rootIndex);
   //Right
   TreeAft(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
   cout<<node->elem<<" ";
   //return;
 }

void TreePre(char inorder[], char aftorder[], int length)
{
    if(length == 0)
    {
        return ;
    }
    TreeNode* node = new TreeNode;//Noice that [new] should be written out.
    node->elem = *(aftorder+length-1);
    cout<<node->elem<<" ";
    int rootIndex = 0;
    while(rootIndex < length)
    {
        if(inorder[rootIndex] ==  *(aftorder+length-1))
            break;
        rootIndex++;
    }

     TreePre(inorder, aftorder , rootIndex);
    TreePre(inorder + rootIndex + 1, aftorder + rootIndex , length - (rootIndex + 1));


}


 int main(int argc, char* argv[])
 {

     char pr[]="ABCDEFGH";  //前序
     char in[]="BDCEAFHG";  //中序
     char aft[]="DECBHGFA"; //后序
     cout<<"求后序遍历:"<<endl;
     TreeAft(in, pr, 8);
     cout<<endl<<"求前序遍历:"<<endl;
     TreePre(in, aft, 8);
     printf("\n");
     return 0;
 }

 //     char* pr="GDAFEMHZ";
     //char* in="ADEFGHMZ";