Answers for "preorder"

C++
1

preorder

void preorder(Node* root){
    if(root != NULL){
        cout<<root->data<<" ";
        preorder(root->left);
        preorder(root->right);
    }
}
Posted by: Guest on August-01-2021
-2

preorder traversal

#include <iostream>
using namespace std;

class node{
public:
    int data;
    node* left;
    node* right;

    node(int d){
        data = d;
        left = NULL;
        right = NULL;
    }
};

node* buildTree(){
    int d;
    cin>>d;

    if(d==-1){
        return NULL;	//to attach a NULL pointer[in case of no child] enter -1
    }
    node * root = new node(d);
    root->left = buildTree();
    root->right = buildTree();
    return root;
}



//REQUIRED FUNCTION: Inorder Traversal


void printIn(node*root){
    if(root==NULL){
        return;
    }
    //Otherwise Left Root Right
    printIn(root->left);
    cout<<root->data<<" ";
    printIn(root->right);
}


int main(){ 
    node* root = buildTree();
    printIn(root);

	return 0;
}

//SAMPLE INPUT TO RUN THE CODE ON ANY ONLINE IDE:
//8 10 1 -1 -1 6 9 -1 -1 7 -1 -1 3 -1 14 13 -1 -1 -1
Posted by: Guest on October-07-2020

Browse Popular Code Answers by Language