• 二叉树的遍历


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

    #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;
    }
  • 相关阅读:
    Flexbox 可视化属性
    latex 数学公式
    迭代器模式 rx 应用
    小程序开发 easy-less 配置
    react-devtool 消息处理渲染 源码理解
    csrf jsonp
    koa1 源码详解1
    Immutable api example
    es6 ajax
    lodash 替换 underscore
  • 原文地址:https://www.cnblogs.com/jiangwang2013/p/3625981.html
Copyright © 2020-2023  润新知