首页 > 代码库 > 二叉树简单实例

二叉树简单实例

// ConsoleApplication2.cpp

//

 

#include "stdafx.h"

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

//Define the Node structure.

struct Node

{

         long item;

         unsigned int count;

         Node *pleft, *pright;

};

 

Node *create_node(long value);

Node *add_node(Node *proot, long value);

void print_node(Node *proot);

void free_node(Node *proot);

 

int _tmain(int argc, _TCHAR* argv[])

{

         Node *proot = NULL;;

         char tempc = ‘\0‘;

         long value = http://www.mamicode.com/0;

         while (1)

         {

                  printf("Do you want to go on? ");

                  scanf_s(" %c", &tempc, sizeof(char));

                  fflush(stdin);

                  if (tolower(tempc) == ‘n‘)

                          break;

                  printf("Enter the value: ");

                  scanf_s(" %ld", &value);

                  fflush(stdin);

                  if (proot == NULL)

                          proot = create_node(value);

                  else

                          add_node(proot, value);

         }

         print_node(proot);

         free_node(proot);

         system("pause");

         return 0;

}

//Create a new node.

Node *create_node(long value)

{

         Node *temp = (Node*)malloc(sizeof(Node));

         if (temp != NULL)

         {

                  temp->item = value;

                  temp->count = 1;

                  temp->pleft = NULL;

                  temp->pright = NULL;

         }

         return temp;

}

//Add new node to the root node.

Node *add_node(Node *proot, long value)

{

         if (proot == NULL)

                  return create_node(value);

         if (proot->item == value)

         {

                  ++proot->count;

                  return proot;

         }

         if (value < proot->item)

         {

                  if (proot->pleft == NULL)

                          return proot->pleft = create_node(value);

                  else

                          return add_node(proot->pleft, value);

         }

         else

         {

                  if (proot->pright == NULL)

                          return proot->pright = create_node(value);

                  else

                          return add_node(proot->pright, value);

         }

}

//Print the node values.

void print_node(Node *proot)

{

         for (int i = 0; i < proot->count; ++i)

                  printf("%d\t", proot->item);

         putchar(10);

         if (proot->pleft != NULL)

                  print_node(proot->pleft);

         if (proot->pright != NULL)

                  print_node(proot->pright);

}

//Free the memory storing nodes.

void free_node(Node *proot)

{

         if (proot->pleft != NULL)

                  free_node(proot->pleft);

         if (proot->pright != NULL)

                  free_node(proot->pright);

         free(proot);

}

二叉树简单实例