Skip to content

Instantly share code, notes, and snippets.

@vbifonixor
Last active May 11, 2017 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vbifonixor/4cb88ec87b8161f0ed86cf9e80fadb0c to your computer and use it in GitHub Desktop.
Save vbifonixor/4cb88ec87b8161f0ed86cf9e80fadb0c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct Node{
int key;
struct Node *left;
struct Node *right;
} Node;
typedef Node *PNode;
PNode Root=NULL;
PNode CreateNode (int ke){
PNode NewNode=(PNode)malloc(sizeof(Node));
NewNode->key=ke;
NewNode->left=NULL;
NewNode->right=NULL;
return NewNode;
}
void Insert(PNode New, PNode Base) {
if (Base == NULL) {
Base = New;
}
if (New->key > Base->key)
if (Base->right == NULL)Base->right = New;
else Insert(New, Base->right);
else if (New->key < Base->key)
if (Base->left == NULL)Base->left = New;
else Insert(New, Base->left);
else Base->key = New->key;
}
void input(){
PNode NewNode;
int a;
char ch;
do{
puts ("vvedite kluch");
scanf("%d", &a);
if(Root == NULL) {
Root = CreateNode(a);
}
else {
Insert(CreateNode(a), Root);
}
puts("esche?");
ch=getch();
}
while(ch !='n');
return;
}
void printklp(PNode from){
if (from!=NULL){
printf("%5d \n",from->key);
printklp(from->left);
printklp(from->right);
}
}
void printlkp(PNode from){
if (from!=NULL){
printlkp(from->left);
printf("%5d \n",from->key);
printlkp(from->right);
}
}
void printlpk(PNode from){
if (from!=NULL){
printlpk(from->left);
printlpk(from->right);
printf("%5d \n",from->key);
}
}
void add(){
PNode NewNode;
int a;
puts ("vvedite kluch");
scanf("%d \n", &a);
Insert(CreateNode(a), Root);
}
int leafsOnLevel (int i, PNode startFrom) {
if (i != 0) {
return (leafsOnLevel(i-1, startFrom->left) + leafsOnLevel(i-1, startFrom->right));
}
if (startFrom == NULL) {
puts("ERROR!");
return 0;
}
if(startFrom->left || startFrom->right) {
return 0;
}
return 1;
}
int nodesOnTree(PNode startFrom) {
int i;
if(startFrom == NULL) {
return 0;
}
i = 1 + nodesOnTree(startFrom->left) + nodesOnTree(startFrom->right);
}
int main(){
char c;
int a;
while (1){//clrscr();
puts("a-create a new binary tree");
puts("b-straight traversal");
puts("c-symmetrical traversal");
puts("d-reverse traversal");
puts("e-adding element");
puts("1-count leafs on level");
puts("2-count nodes on whole tree without leafs");
puts("0-exit");
c=getch();
switch(c) {
case 'a':input(); break;
case 'b':printklp(Root); break;
case 'c':printlkp(Root); break;
case 'd':printlpk(Root); break;
case 'e':add(); break;
case '1':
puts ("vvedite uroven");
scanf("%d", &a);
printf("%d\n", leafsOnLevel(a, Root)); break;
case '2':
printf("%d\n", nodesOnTree(Root)); break;
case '0': return 0;
defaults: puts("Wrong mode");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment