Speed up development with full-stack environments for every branch.

Learn More

in order traversal [C++]

Forked from Binary Tree traversal.

12 Runs 41 Views 38 Copies
Saved

Saved

tliu61 4

tliu61
published a year ago

    #include <iostream>
    using namespace std;
    
    
    class Node{
    public:
    	int data;
    	Node* left;
    	Node* right;
    	
    	Node(){
    	}
    	
    	Node(int val){
    		data = val;
    	}
    	
    };
    
    class Queue{
    public:	
    	int rear, front, capacity, size;
    	Node* arr[10];
    	
    	Queue(int cap){
    		rear = front = size = 0;
    		capacity = cap;
    	}
    	
    	void enqueue(Node* n){
    		if(size == capacity){
    			return;
    		}
    		size = size + 1;
    		arr[rear] = n;
    		rear = (rear + 1)% capacity;
    	}
    	
    	Node* dequeue(){
    		if(size == 0){
    			return 0;
    		}
    		size = size - 1;
    		Node* val = arr[front];
    		front = (front + 1)%capacity;
    		return val;
    	}
    	
    };
    
    void inorder(Node* n){
    	if(n == NULL){
    		return;
    	}
    	inorder(n->left);
    	std::cout << n->data;
    	inorder(n->right);
    }
    
    
    
    void printPath(Node* n){
    	Queue* q = new Queue(10);
    	q->enqueue(n);
    	while(q->size > 0){
    		Node* p = q->dequeue();
    		std::cout << p->data;
    		if(p->left != NULL)
    			q->enqueue(p->left);
    		if(p->right != NULL)
    			q->enqueue(p->right);
    	}
    	
    }
    
    int main() {
    	Node* b = new Node(4);
    	b->left = new Node(3);
    	b->right = new Node(5);
    
    	printPath(b);
     	return 0;
    }
    Please login/signup to get access to the terminal.

    Your session has timed out.

    Dismiss (the page may not function properly).