重新学习二叉树作的几道习题

 二叉树习题

 

// Tree2.cpp : 定义控制台应用程序的入口点。
//


#include  <iostream>
#include "stdafx.h"

 

using  namespace  std;


typedef   struct  _TreeNode
{
 char    data;
 _TreeNode*  lChild;
 _TreeNode*  rChild;
}TreeNode,*PTreeNode;


  void  PreWalk(TreeNode*  p)
  {
    if(p == NULL) return;
    cout<< p->data <<endl;
    if(p->lChild != NULL)
       cout<< "left of "<<p->data<<endl;
    PreWalk( p->lChild);
    if( p->rChild != NULL)
       cout<< "righ of " <<p->data<<endl;
    PreWalk(p->rChild);
  }

  void  InWalk(TreeNode*  p)
  {
   if(p == NULL) return;

   if(p->lChild != NULL)
     cout<< "left of "<<p->data<<endl;
   InWalk( p->lChild);

   cout<<p->data<<endl;

   if( p->rChild != NULL)
     cout<< "righ of " <<p->data<<endl;
    InWalk(p->rChild);
  }

  void  PostWalk(TreeNode*  p)
  {
    if(p == NULL) return;

    if(p->lChild != NULL)
     cout<< "left of "<<p->data<<endl;  
    PostWalk( p->lChild);

    if( p->rChild != NULL)
     cout<< "righ of " <<p->data<<endl;
    PostWalk(p->rChild);

    cout<<p->data<<endl;
  }

/*前序输入创建二叉树*/ 
  bool   CreateTree(TreeNode**  pTree)
  {
   char  c;
   cout<<"Value:\n"<<endl;
   cin>>c;
   if( c == '#' )
   {
    *pTree = NULL;
    return  false;//空子树
   }
   else if( c == '$' )
   {
    *pTree = NULL;
    return true;//结束 
   }
   else
   {
    TreeNode*  pNode = new  TreeNode;
    pNode->data = c;
    *pTree = pNode;
    pNode->lChild = pNode->rChild= NULL;
    cout<<"Left of "<<c<<endl;
    if( CreateTree(  &(*pTree)->lChild ))
     return true;
    cout<<"Right of "<<c<<endl;
    if(CreateTree(  &(*pTree)->rChild ))
     return true;

    return false;
   }

  }


 


int _tmain(int argc, _TCHAR* argv[])
{
   TreeNode*   _root = NULL;
   CreateTree(&_root);

   PreWalk( _root);

 return 0;
}

 

posted on 2014-02-26 14:52  bitbit  阅读(266)  评论(0编辑  收藏  举报