12450 - Tsai DS 20191024 Binary Tree   

Description

Construct a complete binary tree with the input number N (N=1~20) and output the preorder traversal, inorder traversal and postorder traversal of the tree.

Ex             N = 5                                                                                                             N=8

Hint: if the parent node is at index i then the left child node is at index (2*i + 1) and the right child node is at index (2*i + 2).

 

#include <iostream>

using namespace std; 

class Node{

    private:

        int val;

        Node* left;

        Node* right;

    public:

        Node(int data):val(data),left(NULL),right(NULL){}

        void setLeft(Node* node){

            this->left=node;

        }

        void setRight(Node* node){

            this->right=node;

        }

        Node* getLeft(){

            return this->left;

        }

        Node* getRight(){

            return this->right;

        }

        int getValue(){

            return this->val;

        }

};

Node* insertLevelOrder(int arr[], Node* root, int i, int n) 

      //TODO

void inOrder(Node* root) { 

    //TODO

void preOrder(Node *root){

      //TODO

}

void postOrder(Node *root){

    //TODO

}

int main() 

    int num;

    cin>>num;

    int arr[20]={0};

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

        arr[i]=i+1;

    }

    Node* root = insertLevelOrder(arr, root, 0, num); 

    inOrder(root); 

    cout<<endl;

    preOrder(root);

    cout<<endl;

    postOrder(root);

    cout<<endl;

}

Input

Output

Sample Input  Download

Sample Output  Download

Tags




Discuss