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);
}