二叉树的遍历与创建

来源:互联网 发布:java.nio jar 下载 编辑:程序博客网 时间:2024/05/19 09:11

二叉树遍历:
递归实现:
void BT_Order(BTreeNode *t)
{

    if(NULL == t)return ;
   
 
    //先序处理插入cout<<t->data<<' ';
    BT_Order(t->lchild);
    //中序处理插入cout<<t->data<<' ';
    BT_Order(t->rchild);
    //后序处理插入cout<<t->data<<' ';
}


非递归实现:(后序遍历???)

void BT_Order(pTreeT root)
{
    stack<treeT *> s;

    while ( root) || !s.empty())
    {
        if (root)
        {
            //若为先序,则插入visit(root);
            s.push(root);
            root = root->left;
        }
        else
        {
            root = s.top();
     //若为中序,插入visit(root);
            s.pop();
            root = root->right;
        }
    }
}


层次遍历:
void BT_LevelOrder(pTreeT root)
{
    queue<treeT *> q;
    treeT *treePtr;

    assert( NULL != root );

    q.push(root);

    while (!q.empty())
    {
        treePtr = q.front();
        q.pop();
        visit(treePtr);

        if (NULL != treePtr->left)
        {
            q.push(treePtr->left);   
        }
        if (NULL != treePtr->right)
        {
            q.push(treePtr->right);
        }   
           
    }
}

 

创建二叉树
void creat_BT(tree &t)
{
  char ch;
 
 cin>>ch;
  if(ch == '0')
  {
      t=NULL;
  }
  else
  {
      t = new binary_tree;
      if(!t) exit(0); //如果没成功申请空间 则退出

      t->data=ch;
            creat_tree(t->lchild);
      creat_tree(t->rchild);
  }
 
}

 

原创粉丝点击