zoukankan      html  css  js  c++  java
  • 二叉搜索树

     1 #include <iostream>
     2 using namespace std;
     3 typedef struct node
     4 {
     5     int value;
     6     node *lchild,*rchild;
     7 }*bitree,binode;
     8 /*寻找要插入的双亲结点*/
     9 bool searchBSD(bitree root,int data,bitree f,bitree &p)        /*传引用,f为双亲结点*/
    10 {    
    11     if(!root)
    12     {
    13         p=f;
    14         return false;
    15     }
    16     else if(root->value==data)
    17     {
    18         p=root;
    19         return false;
    20     }
    21     else if(data<root->value)
    22         return searchBSD(root->lchild,data,root,p);
    23     else
    24         return searchBSD(root->rchild,data,root,p);
    25 }
    26 void InsertBST(bitree &root,int data)        /*结点插入*/
    27 {
    28     bitree p,temp;        /*p为被插入的结点,temp为即将插入的结点*/
    29     if(!searchBSD(root,data,NULL,p))
    30     {
    31         temp=new binode;
    32         temp->value=data;
    33         temp->rchild=temp->lchild=NULL;
    34         if(p==NULL)
    35             root=temp;
    36         else if(p->value>data)
    37             p->lchild=temp;
    38         else
    39             p->rchild=temp;
    40     }
    41 }
    42 void InOrderTraverse(bitree root)    /*中序遍历二叉搜索树*/
    43 {
    44     if(root)
    45     {
    46         InOrderTraverse(root->lchild);
    47         cout<<root->value<<" ";
    48         InOrderTraverse(root->rchild);
    49     }
    50 }
    51 int main(int argc, char const *argv[])
    52 {
    53     bitree root;
    54     int n;
    55     int a[100];
    56     while(cin>>n)
    57     {
    58         root=NULL;
    59         for(int i=0;i<n;i++)
    60         {
    61             cin>>a[i];
    62             InsertBST(root,a[i]);
    63         }
    64         InOrderTraverse(root);
    65     }    
    66     
    67     return 0;
    68 }
  • 相关阅读:
    【面试题】M
    【转】C/S,B/S区别
    【转】指针和引用的区别
    内联函数
    实习-随记
    【面试】http协议知识
    wenbenfenlei
    【面试】链表反转
    测试面试题2
    测试面试题
  • 原文地址:https://www.cnblogs.com/a1225234/p/4782296.html
Copyright © 2011-2022 走看看