有序二叉树的操作

 

2. 有序二叉树指的是左孩子结点值小于右孩子结点值的二叉树。请实现有序二叉树的以下操作,并编写对应的测试代码:
Tree.h
#include<stdio.h>
#include<stdlib.h>
 
typedef struct TREE
{   int val;
       struct TREE *left;
       struct TREE *right;
}node;
 
#define len    sizeof(node)
 
 
 
#include "tree.h"
node* share(node **pp , int key ) / / 公用函数,功能为找到值为key的节点的位置;
{
       node *parent;
       parent=*pp;   
       while(*pp!=NULL&&(*pp)->val!=key)
       {
              if((*pp)->val > key)    //val的值大于key,insert left;
              {
                     parent = *pp;     保存指针
                     *pp = (*pp)->left;
              }
              else
              {
                     parent=*pp;//insert right;
                     *pp=(*pp)->right;
              }
       }
       return parent;//parent is the node
}     
- 2.1 插入函数insert()
node* insert(node *p,int key)
{
     node *root,*pf,*parent,*child;
     int t=key; //要插入的值为key 's node
     root=pf=p;     
     if(root==NULL)//顺序二叉树为空,创建根节点,相当于插入第一个节点;
     {
            root=(node *)malloc(len);
            root->val=key;
            root->left=NULL;
            root->right=NULL;
            return root;//return the head node;
     }
    /*the &pf is a pointer to pointer*/
     parent= share(&pf,t);//通过share函数可以确定要找到节点位置 ;
     if(pf==NULL)
     {
            child=(node *)malloc(len);//child is the insert node;
            child->val=key;
            child->left=NULL;
            child->right=NULL;
            /*if the p's val > c's val ,insert to left */
            if(parent->val>child->val)
                   parent->left=child;
            else//opposite;
                   parent->right=child;
     }  
     return root;//return the head node ;
}
- 2.2 查找函数find()
#include "tree.h"
void find(node *p,int key)
     node *pf,*parent;
     int t=key;
     pf=parent=p;  
     parent=share(&pf,t);
     if(pf==NULL)
            printf("there is not this node in the tree!/n");
     else
            printf("I find the %dth node in this tree/n",pf->val);
 
}    
- 2.3 查找父结点函数find_parent()
#include "tree.h"
void find_parent(node *p,int key)
{
     node *pf,*parent;
     int t=key;
     pf=parent=p;  
     parent=share(&pf,t);
     if(pf==NULL)
            printf("there is not this node in the tree!/n");
     else
            (pf->val==parent->val)? /
          printf("this is root node,it is no parent node!/n"):/
          printf(" the %dth node's parent node is %dth node /n",/
          pf->val,parent->val);
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值