二叉树的遍历

//先序
void preOrder(TreeNode* root)
{
    if(root == nullptr)
        return;
    
    stack<TreeNode*> s;
    auto p = root;
    while(p||!s.empty())
    {
        while(p)
        {
            cout<<p.val<<endl;
            s.push(p);
            p = p->left;
        }

        if(!s.empty())
        {
            auto node = s.top();
            s.pop();
            p = node->right;
        }
    }
}

//中序
void inOrder(TreeNode* root)
{
    if(root == nullptr)
        return;
    
    stack<TreeNode*> s;
    auto p = root;
    while(p||!s.empty())
    {
        while(p)
        {
            s.push(p);
            p = p->left;
        }
        if(!s.empty())
        {
            auto node = s.top();
            s.pop();
            cout<<node.val<<endl;
            p = node->right;
        }
    }
}

//后序
void postOrder(TreeNode* root)
{
    if(root == nullptr)
        return;

    stack<TreeNode*> s;
    auto p = node;
    TreeNode* prev = nullptr;
    while(p||!s.empty())
    {
        while(p)
        {
            s.push(p);
            p = p->left;
        }

        if(!s.empty())
        {
            auto node = s.top();
            s.pop();
            if(!node->right || node->right == prev)
            {
                cout<<node->val;
                prev = node;
            }
            else
            {
                s.push(node);
                p = node->right;
            }
        }
    }
}
posted @ 2019-10-24 14:56  JohnRed  阅读(94)  评论(0编辑  收藏  举报