您的位置:首页 > 其它

二叉树的深度优先,广度优先,以及层次遍历算法

2015-09-17 13:20 681 查看
深度优先算法

void deepFirstSearch(Tree root)
{
stack<node*>nodestack;
nodestack.push(root);
Node *node;
while(!nodeStack.Empty())
{
node=nodestack.top();
node.stcakpop();
printf();
if(node->rchild)
{
nodestack.push(node->rchild);
}
if(node->lchild)
{
nodestack.push(node->lchild);
}
}
}


广度优先算法

void breathFirstSearch(Tree root)
{
Queue<Node *>Nodequeue;
Nodequeue.push(root);
Node *node;
while(!NodeQueue.Empty())
{
node=NodeQueue.front;
NodeQueue.pop();
printf();
if(node->lchild)
{
NodeQueue.push(node->lchild);
}
if(node->rchild)
{
NodeQueue.push(node->rchild);
}
}
}


层次遍历算法

void levelFirstSearch(Tree T,int level)
{
if(level<0||T==NULL)
{
return -1;
}
if(level==0)
{
printf(T);
}
else
{
return levelFirstSearch(T->lchild,level-1) +
levelFirstSearch(T->rchild,level-1)
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: