首页 > 其他 > 详细

二叉树的遍历

时间:2014-03-26 17:51:21      阅读:395      评论:0      收藏:0      [点我收藏+]

二叉树的遍历可以使用递归,循环的方式遍历,一下列出了使用栈和队列的方式循环遍历二叉树的方式。

bubuko.com,布布扣
#include "stdafx.h"
#include <stack>
#include <queue>
using namespace std;


struct TreeNode
{
    TreeNode()
    {
        memset(this, 0, sizeof(*this));
    }
    TreeNode* pLeft;
    TreeNode* pRight;
    int m_nValue;
};

/* 递归遍历 */
void TreeOrder(TreeNode* root)
{
    if (NULL == root)
    {
        return ;
    }
    printf("%d ", root->m_nValue);
    TreeOrder(root->pLeft);
    TreeOrder(root->pRight);
}

/* 使用栈循环遍历 */
void TreeOrderStack(TreeNode* root)
{
    if (NULL == root)
    {
        return ;
    }
    stack<TreeNode*> s;
    s.push(root);

    while (!s.empty())
    {
        TreeNode* pNode = s.top();
        s.pop();
        printf("%d ",pNode->m_nValue);
        if (NULL != pNode->pLeft)
        {
            s.push(pNode->pLeft);
        }
        if (NULL != pNode->pRight)
        {
            s.push(pNode->pRight);
        }
    }
}

/* 使用队列循环遍历 */
void TreeOrderQueue(TreeNode* root)
{
    if (NULL == root)
    {
        return ;
    }
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty())
    {
        TreeNode* pNode = q.front();
        q.pop();
        printf("%d ", pNode->m_nValue);
        if (NULL != pNode->pLeft)
        {
            q.push(pNode->pLeft);
        }
        if (NULL != pNode->pRight)
        {
            q.push(pNode->pRight);
        }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}
bubuko.com,布布扣

二叉树的遍历,布布扣,bubuko.com

二叉树的遍历

原文:http://www.cnblogs.com/jiangwang2013/p/3625981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!