Output the binary tree
The tree: 60 30 80 20 40
Desired Output:
__________60
________/____\
______30______80
_____/_______/
____20______40
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include<iostream>
using namespace std;
struct node
{
int info;
struct node *left, *right;
};
struct node *newNode(int num)
{
struct node * node = (struct node*)malloc(sizeof(struct node));
node->info = num;
node->left = NULL;
node->right = NULL;
return node;
}
void inorder(struct node *);
void postorder(struct node *);
void preorder(struct node *);
//void print(struct node *root, int num)
//{
// int level = 0;
// if (root<num)
//
//}
int main()
{
int choice;
struct node *root = newNode(60);
root->left = newNode(30);
root->right = newNode(80);
root->left->left = newNode(20);
root->left->right = newNode(40);
menu:
cout << "=================================\n";
cout << " [1] Inorder\n";
cout << " [2] Postorder\n";
cout << " [3] Preorder\n";
cout << " [4] Exit\n";
cout << "=================================\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "=================================\n";
cout << "Inorder Traversal: ";
inorder(root);
system("pause>0");
system("cls");
goto menu;
break;
case 2:
cout << "=================================\n";
cout << "Postorder: ";
postorder(root);
system("pause>0");
system("cls");
goto menu;
break;
case 3:
cout << "=================================\n";
cout << "Preorder: ";
preorder(root);
system("pause>0");
system("cls");
goto menu;
break;
case 4:
exit(1);
default:
cout << "=================================\n";
cout << "Invalid choice!";
}
system("pause>0");
return 0;
}
|
I did this and it does not work
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
void print(int num)
{
int temp;
temp = num;
if (num < temp)
cout << num;
else if (num>temp)
cout << " " << num;
print(num);
}
int main()
{
int choice, n;
struct node *root = newNode(n = 60);
root->left = newNode(n = 30);
root->right = newNode(n = 80);
root->left->left = newNode(n = 20);
root->left->right = newNode(n = 40);
print(n);
|
Topic archived. No new replies allowed.