二叉树的一些简单操作

来源:互联网 发布:精良分班软件 编辑:程序博客网 时间:2024/06/05 16:02

二叉树(Binary Trees)在数据结构与算法中占有很重要的位置,下面我介绍一些二叉树的简单的基础的东西:

1.二叉树的建立:

二叉树的基础是链表,在单链表中其指针域存储了一个指向一个节点的指针,但是在二叉树中,除了根节点和叶子节点之外,都具有双亲节点和子节点,所以每一个节点都有两个指向下一个节点的指针,另外声明时其内还需要声明数据域来存储数据,所以其结构体的定义如下:


生成一棵二叉树首先需要有根节点,然后再创建其他子节点,在创建其他节点时,我们从根节点开始比较其值,我们将比根节点大的放在右子树上,其他的放在左子树上,这里需要两个指针连动,指针cur指向当前节点,front指向上一个节点,cur向NULL跑,当跑完的时候front指针就确定了插入的位置,so,let's show codes!

/*建立二叉树*/typedef struct node{    struct node *left; //指向左子树    struct node *right;//指向右子树    int data;// 数据域}binTree;binTree *creatBinaryTree(int *a,int n){    binTree *root,*newNode,*cur,*Front;    int i;    for(i=0;i<n;i++){        cur=root;//从根开始比较        newNode=(binTree*)malloc(sizeof(binTree));        newNode->data=a[i];        newNode->left=newNode->right=NULL;        if(i==0) root=newNode;//创建根节点        else{            while(cur!=NULL){ //front指针和cur指针连动确定插入位置                Front=cur;                if(newNode->data<=cur->data)                    cur=cur->left;                else                    cur=cur->right;            }            if(newNode->data>Front->data)                    Front->right=newNode;            else                Front->left=newNode;        }    }    return root;}
2.二叉树的遍历:

二叉树的其实是递归的产物,遍历二叉树其实就是递归这棵二叉树,遍历中分为前序遍历,中序遍历,后序遍历
         a.前序遍历:“访根访左访右”:

void printBinaryTree(binTree *root) //前序遍历{    if(root!=NULL){        printf("%-3d",root->data); //访根        printBinaryTree(root->left);//访左        printBinaryTree(root->right);//访右            }}


         b.中序遍历:“访左访根访右”:

void printBinaryTree(binTree *root) //中序遍历{    if(root!=NULL){        printBinaryTree(root->left);//访左        printf("%-3d",root->data); //访根        printBinaryTree(root->right);//访右            }}



      c.后序遍历:“访左访右访根”:


void printBinaryTree(binTree *root) //后序遍历{    if(root!=NULL){        printBinaryTree(root->left);//访左        printBinaryTree(root->right);//访右        printf("%-3d",root->data); //访根    }}


  二叉树的操作很多都是基于递归方式完成的,在操作二叉树的时候,能够做到“心中有树”很多问题都能很好的解决掉,so just do it!

0 0
原创粉丝点击