`
xitonga
  • 浏览: 585875 次
文章分类
社区版块
存档分类
最新评论

二叉树的遍历与创建

 
阅读更多

二叉树遍历:
递归实现:
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);
}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics