二叉树-链表实现

writer:pprp

二叉树,基础数据结构,通过一个数组,将其转化为一个二叉树;

完成的主要是:1,向树中插入一个新的节点;

       2,创建一个新的树;

         3,将其打印出来,三种方式遍历;

#include <iostream>

using namespace std;

struct tree
{
    tree * left;
    int val;
    tree * right;
};

//插入操作,比根节点大,放到右边,比根节点小,放到左边;
tree * insert(tree * root,int val)
{
    tree * current;
    tree * parent;
    tree * newval = new tree();

    newval->left = NULL;
    newval->right = NULL;
    newval->val = val;

    if(root == NULL)
    {
        root = newval;
    }
    else
    {
        current = root;
        while(current!=NULL)      //找到应该插入的位置
        {
            parent = current;
            if(current->val > val)
            {
                current = current->left;
            }
            else
            {
                current = current->right;
            }
        }                            //通过比较进行插入
        if(parent->val > val)
        {
            parent->left = newval;
        }
        else
        {
            parent->right = newval;
        }

    }
    return root;
}
//通过一个数组,和他的长度来创造一个二叉树
tree * create(int * val,int len)
{
    tree * root = NULL;
    for(int i = 0 ; i < len ; i++)
    {
        root = insert(root,val[i]);
    }
    return root;
}

//通过递归遍历一个二叉树,将其打印出来
//先序遍历
void leftprint(tree * root)
{
    if(root!=NULL)
    {
        cout << root->val << " ";
        leftprint(root->left);
        leftprint(root->right);
    }
}
//中序遍历
void midprint(tree * root)
{
    if(root!=NULL)
    {
        midprint(root->left);
        cout << root->val << " ";
        midprint(root->right);
    }
}

//后序遍历
void rightprint(tree * root)
{
    if(root!=NULL)
    {
        rightprint(root->left);
        rightprint(root->right);
        cout << root->val << " ";
    }
}
int main()
{
    int a[] = {0,1,2,3,4,5};

    tree * root = create(a,6);
    
    
    cout <<"先序遍历:"<<endl;
    leftprint(root);
    cout << endl;
    
    cout <<"中序遍历:"<<endl;
    midprint(root);
    cout << endl;
    
    cout <<"后序遍历:"<<endl;
    rightprint(root);
    cout << endl;

    return 0;
}

 

posted @ 2017-07-21 17:11  pprp  阅读(329)  评论(0编辑  收藏  举报