zoukankan      html  css  js  c++  java
  • 二叉树的遍历

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

    #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;
    }
  • 相关阅读:
    go-go协程
    linux-pclint代码检测
    linux-32位-交叉编译openssl
    go-json类
    mysql-定时任务
    go-IO操作
    go-异常处理-error-panic-recover
    go-defer语句
    go-select
    go-指针
  • 原文地址:https://www.cnblogs.com/jiangwang2013/p/3625981.html
Copyright © 2011-2022 走看看