您的位置:首页 > 其它

二叉树的遍历(1):前序遍历

2015-06-04 10:31 302 查看
#include <iostream>
#include <stack>
#include <queue>
using namespace std;

typedef int TreeNodeElem;

struct TreeNode 
{
    TreeNode* left;
    TreeNode* right;
    TreeNodeElem elem;
};

//递归遍历
void preOrder_R(TreeNode* root, int(*visit)(TreeNode*))
{
    if (root == nullptr)
    {
        return;
    }
    visit(root);
    preOrder_R(root->left, visit);
    preOrder_R(root->right, visit);
}

//非递归遍历
void preOrder(TreeNode* root, int(*visit)(TreeNode*))
{
    TreeNode* p = root;
    stack<TreeNode*> s;
    if (p != nullptr)
    {
        s.push(p);
    }
    while (!s.empty())
    {
        p = s.top();
        s.pop();
        visit(p);
        if (p->right != nullptr)
        {
            s.push(p->right);
        }
        if (p->left != nullptr)
        {
            s.push(p->left);
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: