Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

#include <iostream>

#include <vector>

using namespace std;

int height = 0;

bool bin = true;

class Node {

public:

int data;

vector<Node *> child;

};

void add_child (Node* head, int parent, int add) {

if (head->data == parent) {

Node* new_node = new Node;

new_node->data = add;

head->child.push_back(new_node);

return;

for (int i = 0 ; i < head->child.size() ; i++) {

add_child(head->child[i], parent, add);

void find_height (Node* head, int h) {

if (head->child.size() == 0) {

if (h > height) height = h;


return;

for (int i = 0 ; i < head->child.size() ; i++) {

find_height(head->child[i], h + 1);

void preorder_traversal (Node* head) {

cout << head->data << ' ';

for (int i = 0 ; i < head->child.size() ; i++) {

preorder_traversal(head->child[i]);

void postorder_traversal(Node* head) {

for (int i = 0 ; i < head->child.size() ; i++) {

postorder_traversal(head->child[i]);

cout << head->data << ' ';

void binary_check(Node* head) {

if (head->child.size() > 2) {

bin = false;

return;

for (int i = 0 ; i < head->child.size() ; i++) {

binary_check(head->child[i]);

}
}

void inorder_traversal(Node* head) {

if (head == NULL) {

return;

if (head->child.size() == 2) {

inorder_traversal(head->child[0]);

cout << head->data << ' ';

inorder_traversal(head->child[1]);

if (head->child.size() == 1) {

inorder_traversal(head->child[0]);

cout << head->data << ' ';

if (head->child.size() == 0) {

cout << head->data << ' ';

int main() {

int N, M;

cin >> N >> M;

Node* head = new Node;

if (N == 1) {

cin >> head->data;

for (int i = 0 ; i < M ; i++) {

int temp, parent;


if (i == 0) {

cin >> head->data;

cin >> temp;

Node* new_node = new Node;

new_node->data = temp;

head->child.push_back(new_node);

else {

cin >> parent >> temp;

add_child(head, parent, temp);

find_height(head, 0);

cout << height << endl;

preorder_traversal(head);

cout << endl;

postorder_traversal(head);

cout << endl;

binary_check(head);

if (bin == false) cout << "NOT BINARY TREE";

else {

inorder_traversal(head);

return 0;
}

You might also like