码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树前中后、层次遍历

时间:2019-05-23 21:18:19      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:pac   bsp   visit   out   cout   ted   post   lse   span   

 

#include<iostream>
#include<stack>
#include<queue>
using namespace std;

/*
二叉树遍历算法递归+非递归:
前序遍历:根->左->右
中序遍历:左->根->右
后序遍历:左->右->根
层次遍历
*/
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x): val(x),left(NULL),right(NULL) {}
};

/*递归版本*/
void prerecusive(TreeNode *root)
{
    if (!root) return;
    cout << root->val << " ";
    prerecusive(root->left);
    prerecusive(root->right);
}
void inrecusive(TreeNode *root)
{
    if (!root) return;
    inrecusive(root->left);
    cout << root->val << " ";
    inrecusive(root->right);
}
void postrecusive(TreeNode *root)
{
    if (!root) return;
    postrecusive(root->left);
    postrecusive(root->right);
    cout << root->val << " ";
}

/*循环版本。栈做辅助*/
void preiteration(TreeNode *root)
{
    if (!root) return;
    stack<TreeNode *> s;
    s.push(root);
    while (!s.empty())
    {
        cout << s.top()->val << " ";
        s.pop();
        if (root->right) s.push(root->right);
        if (root->left) s.push(root->left);
    }
}
void initeration(TreeNode *root)
{
    if (!root) return;
    stack<TreeNode *> s;
    TreeNode *curr = root;
    while (curr || !s.empty())//s没有值,第一个判断条件是curr不是空
    {
        if (curr)
        {
            s.push(curr);
            curr = curr->left;
        }
        else
        {
            cout << s.top()->val << " ";
            curr = s.top()->right;
            s.pop();
        }
    }
}
void postiteration(TreeNode *root)
{
    if (!root) return;
    stack<TreeNode *> s;
    s.push(root);
    TreeNode *curr;
    TreeNode *visited;//记录子节点已经访问过
    while (!s.empty())
    {
        curr = s.top();
        /*
         * 出栈条件:
         * 对于叶子节点:直接弹出
         * 对于非叶子节点:如果已经遍历过其左子节点或右子节点,则弹出
         */
        if ((!curr->left && !curr->right) || (visited && (curr->left==visited || curr->right == visited)))
        {
            cout << curr->val << " ";
            visited = curr;
            s.pop();
        }
        else
        {
            if (curr->right) s.push(curr->right);
            if (curr->left) s.push(curr->left);
        }
    }
}

void leveltraverse(TreeNode *root)
{
    if (!root) return;
    queue<TreeNode *> q;
    TreeNode *curr;
    q.push(root);
    while (!q.empty())
    {
        curr = q.front();
        cout << curr->val << " ";
        q.pop();
        if (curr->left) q.push(curr->left);
        if (curr->right) q.push(curr->right);
        
    }
}

 

二叉树前中后、层次遍历

标签:pac   bsp   visit   out   cout   ted   post   lse   span   

原文地址:https://www.cnblogs.com/beixiaobei/p/10914253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!