二叉树的前序,中序遍历

前序递归于循环

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

struct TreeNode
{
    int val;
    TreeNode *left,*right;
};

void create(TreeNode *&p)
{
    int k;
    cin>>k; //1 2 0 0 3 0 0;
    if(k!=0)
    {
        p=new TreeNode;
        p->val=k;
        create(p->left);
        create(p->right);
    }
    else
        p=NULL;
}

void preorder1(TreeNode *p)
{
    if(p)
    {
        cout<<p->val;
        preorder1(p->left);
        preorder1(p->right);
    }
}

void preorder2(TreeNode *root)
{
    stack<TreeNode*> s;
    TreeNode *p=root;
    while(p||!s.empty())
    {
        if(p)
        {
            s.push(p);
            cout<<p->val;
            p=p->left;
        }
        else
        {
            p=s.top();
            s.pop();
            p=p->right;
        }
    }
}

中序递归与循环

void inorder1(TreeNode *p)
{
    if(p)
    {
        inorder1(p->left);
        cout<<p->val;
        inorder1(p->right);
    }
}

void inorder2(TreeNode *p)
{
    stack<TreeNode*> s;
    while(p||!s.empty())
    {
        if(p)
        {
            s.push(p);
            p=p->left;
        }
        else
        {
            p=s.top();
            cout<<p->val;
            s.pop();
            p=p->right;
        }
    }
}

int main()
{
    TreeNode *root=new TreeNode;
    create(root);
    //preorder1(root);
    preorder2(root);
    //inorder1(root);
    inorder2(root);
    return 0;
}

 层次优先遍历

void levelorder(TreeNode *root)
{
    deque<TreeNode*> d;
    TreeNode *p=root;
    d.push_back(p);
    while(!d.empty())
    {
        p=d.front();
        cout<<p->val;
        d.pop_front();
        if(p->left)
            d.push_back(p->left);
        if(p->right)
            d.push_back(p->right);
    }
}

深度优先遍历

void depthorder(TreeNode *root)
{
    stack<TreeNode*> s;
    TreeNode *p=root;
    s.push(p);
    while(!s.empty())
    {
        p=s.top();
        cout<<p->val;
        s.pop();
        if(p->right)
            s.push(p->right);
        if(p->left)
            s.push(p->left);
    }
}

 

posted @ 2017-08-06 20:43  home普通的人  阅读(174)  评论(0编辑  收藏  举报