美文网首页
二叉树的建立-三种遍历

二叉树的建立-三种遍历

作者: 写代码不如跳舞 | 来源:发表于2017-08-25 16:34 被阅读0次

简单粗暴的方式建立了一个结点值依次为1,2,3,4,6,7 的满二叉树,方便验证关于二叉树的算法。

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

struct Node
{
    int val;
    Node *lc;
    Node *rc;
};

void creat(Node *&head)
{
    head = (Node*)malloc(sizeof(Node)); head->val = 1;
    
    head->lc = (Node*)malloc(sizeof(Node)); head->lc->val=2;
    head->rc = (Node*)malloc(sizeof(Node)); head->rc->val=3;
    
    head->lc->lc =(Node*)malloc(sizeof(Node)); head->lc->lc->val =4;
    head->lc->rc =(Node*)malloc(sizeof(Node)); head->lc->rc->val =5;
    head->rc->lc =(Node*)malloc(sizeof(Node)); head->rc->lc->val =6;
    head->rc->rc =(Node*)malloc(sizeof(Node)); head->rc->rc->val =7;
    
    head->lc->lc->lc= NULL;
    head->lc->lc->rc= NULL;
    head->lc->rc->lc= NULL;
    head->lc->rc->rc= NULL;
    head->rc->lc->lc= NULL;
    head->rc->lc->rc= NULL;
    head->rc->rc->lc= NULL;
    head->rc->rc->rc= NULL;
}

void preorder(Node *head)
{
    if(head!=NULL)
    {
        cout<<head->val<<" ";
        
        preorder(head->lc);
        preorder(head->rc);
    }
}

void inorder(Node *head)
{
    if(head!=NULL)
    {
        inorder(head->lc);
        
        cout<<head->val<<" ";
        
        inorder(head->rc);
    }
}

void postorder(Node *head)
{
    if(head!=NULL)
    {
        postorder(head->lc);        
        postorder(head->rc);
        
        cout<<head->val<<" ";
    }
}

void forPreorder(Node *head)
{
    stack<Node*>s;
    if(head == NULL) return;
    else s.push(head);
    
    while(s.size()!=0)
    {
        Node *tmp;
        tmp = s.top();
        cout<<tmp->val<<" ";
        s.pop();
        if(tmp->rc!=NULL) s.push(tmp->rc);
        if(tmp->lc!=NULL) s.push(tmp->lc);  
    }
}

void forinorder(Node *head)
{
    stack<Node*>s;
    Node *cur;
    if(head == NULL) return;
    else 
    {
        cur = head;
    }
    
    while(s.size()!=0 || cur!=NULL)
    {
        if(cur!=NULL)
        {
            s.push(cur);
            cur = cur->lc;
        }
        else
        {
            Node *tmp;
            tmp = s.top();
            cout<<tmp->val<<" ";
            s.pop();
            cur = tmp->rc;
        }
    }
}

int main()
{
    Node *head;
    creat(head);
    
    preorder(head);
    cout<<endl;
    
    inorder(head);
    cout<<endl;
    
    postorder(head);
    cout<<endl;
    
    forPreorder(head);
    cout<<endl;
    
    forinorder(head);
    cout<<endl;
    
    return 0;
}

相关文章

网友评论

      本文标题:二叉树的建立-三种遍历

      本文链接:https://www.haomeiwen.com/subject/slzudxtx.html