CS301p Assignment 2 Solution Spring 2023

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

CS301p Assignment 2 Solution

#include <iostream>
#include <stack>
using namespace std;

template <typename T>


class TreeNode {
public:
    T data;
    TreeNode<T>* left;
    TreeNode<T>* right;

    TreeNode(T data) {
        this->data = data;
        left = NULL;
        right = NULL;
    }

    void insert(T data) {


        if (data < this->data) {
            if (left == NULL) {
                left = new TreeNode<T>(data);
            } else {
                left->insert(data);
            }
        } else {
            if (right == NULL) {
                right = new TreeNode<T>(data);
            } else {
                right->insert(data);
            }
        }
    }

    void inOrder(stack<T> &s) {


        if (left != NULL) {
            left->inOrder(s);
        }
        s.push(data);
        if (right != NULL) {
            right->inOrder(s);
        }
    }

    void preOrder(stack<T> &s) {


        s.push(data);
        if (left != NULL) {
            left->preOrder(s);
        }
        if (right != NULL) {
            right->preOrder(s);
        }
    }

    void postOrder(stack<T> &s) {


        if (left != NULL) {
            left->postOrder(s);
        }
        if (right != NULL) {
            right->postOrder(s);
        }
        s.push(data);
    }
};

int main() {
    stack<int> s;
    TreeNode<int>* root = new TreeNode<int>(11);
    root->insert(6);
    root->insert(15);
    root->insert(4);
    root->insert(8);
    root->insert(13);
    root->insert(19);
    root->insert(16);

    cout << "Reverse Order of In-Order Travsersal" << endl;


    root->inOrder(s);
    while (!s.empty()) {
        cout << s.top() << endl;
        s.pop();
    }

    cout << "Reverse Order of Pre-Order Travsersal" << endl;


    root->preOrder(s);
    while (!s.empty()) {
        cout << s.top() << endl;
        s.pop();
    }

    cout << "Reverse Order of Post-Order Travsersal" << endl;


    root->postOrder(s);
    while (!s.empty()) {
        cout << s.top() << endl;
        s.pop();
    }
    return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy