Question

In: Computer Science

Tree Traversals It should be noted that, in class, all traversal methods were written as recursive...

Tree Traversals It should be noted that, in class, all traversal methods were written as recursive algorithm (i.e. at some point, the method called itself). It is possible to implement non-recursive versions of preorder, inorder, and postorder traversal methods mentioned in class. One intuitive way is by using a stack.
1) Give written pseudocode/explanation of :
a) How to build the tree such that a given non-recursive traversal method can be used.
b) Your algorithm for a non-recursive preorder, inorder, OR postorder traversal method (You only have to pick one)
2) Implement the above mentioned algorithms. Traversals should print out nodes in their required order.

Solutions

Expert Solution

In-order Non-recursive using stack -

#include<bits/stdc++.h>
using namespace std;
struct Node
{
   int val;
   struct Node *left;
   struct Node *right;
   Node (int key)
   {
       this->val=key;
       this->left=this->right=NULL;
   }
};

void printInorderIterative(struct Node *root)
{
   stack <Node *> s;
   struct Node *curr;
   curr=root;
   int flag=0;
   while(!flag)
   {
       if(curr)
       {
           s.push(curr);
           curr=curr->left;
       }
       else
       {
           if(!s.empty())
           {
               curr=s.top();
               s.pop();
               cout<<curr->val<<"\t";
               curr=curr->right;  
           }
           else
           {
               flag=1;
               return ;
           }
       }
   }
  
}
int main()
{
   struct Node *root;
   root=new Node(1);
   root->left=new Node(2);
   root->right=new Node(3);
   root->left->left= new Node(4);
   root->left->right=new Node(5);
   root->left->right->right= new Node(8);
   root->right->left= new Node(6);
   root->right->right= new Node(7);
   cout<<"Iterative Inorder Traversal is "<<endl;
   printInorderIterative(root);
   cout<<endl;
}

Postorder non-recursive using stack

#include <bits/stdc++.h>
using namespace std;

struct Node
{
   int data;
   Node *left, *right;
  
   Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};

void postorderIterative(Node* root)
{
   stack<Node*> s;
   s.push(root);
   stack<Node*> out;
   struct Node *curr;
   while(!s.empty())
   {
       curr=s.top();
       out.push(curr);
       s.pop();
       if(curr->right)
       {
           s.push(curr->right);
       }
       if(curr->left)
       {
           s.push(curr->left);
       }
   }
   while(!out.empty())
   {
       curr=out.top();
       cout<<curr->data<<" ";
       out.pop();
   }
}

int main()
{
   Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
   root->right->right = new Node(6);
   root->right->left->left = new Node(7);
   root->right->left->right = new Node(8);
   cout<<"Postorder traversal of the tree is "<<endl;
   postorderIterative(root);

   return 0;
}

Preorder non-recursive using stack

//preorder binary tree iterative traversal
#include<bits/stdc++.h>
using namespace std;

struct Node
{
   int data;
   Node *left, *right;
  
   Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};

void preOrderIterative(struct Node *root)
{
   stack <Node *> s;
   struct Node *curr;
   s.push(root);
   curr=s.top();
   while(!s.empty())
   {
       curr=s.top();
       s.pop();
       cout<<curr->data<<"\t";
       if(curr->right)
       {
           s.push(curr->right);
       }
       if(curr->left)
       {
           s.push(curr->left);
       }
   }
}
int main()
{
  
   Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->left = new Node(7);
root->right->left->right = new Node(8);
cout<<"Iterative Preoder traversal is "<<endl;
preOrderIterative(root);
return 0;
}


Related Solutions

This program is written in Java and should be modularized in methods in one class. This...
This program is written in Java and should be modularized in methods in one class. This program will calculate the Gross Earnings, FICA tax (Medicare and Social Security taxes), Federal Tax Withheld, and Net Amount of the payroll check for each employee of a company. The output must contain numbers with 2 decimal places. The user input must be validated – if incorrect data is entered, send an error message to the user. INPUT The application must be able to...
**** All these methods should be implemented using RECURSIVE solutions (no looping statements) // Java //...
**** All these methods should be implemented using RECURSIVE solutions (no looping statements) // Java // This method takes an integer array as well as an integer (the starting // index) and returns the sum of the squares of the elements in the array. // This method uses recursion. public int sumSquaresRec(int[] A, int pos) { // TODO: implement this method        return -1; // replace this statement with your own return }    // This method takes a...
Please ready a program should output Inorder Tree Traversal without recursion and without stack!, output in...
Please ready a program should output Inorder Tree Traversal without recursion and without stack!, output in ALGOL W programming only. Thumbs down for wrong answers Make a program to perform Heap Sort, must run in Alice programming only. Only correct answers needed should be in given language
1. During the class lectures, it was noted that fallacies, in almost all cases, usually can...
1. During the class lectures, it was noted that fallacies, in almost all cases, usually can be reflected as emotionally believable while in reality they are: Select one: a. Deductive b. Deductively incoherent c. Sufficiently critical d. Rationally imperfect . 2. While reviewing fallacies, the fallacy of appeal to an individual is usually thought of as discarding a claim by which of the following: Select one: a. Disapproving the individual who creates it b. Creating made-up announcements c. Exercising speechmaking...
Implement the following methods. Assume that these will be methods within your myArray class. operator[] Should...
Implement the following methods. Assume that these will be methods within your myArray class. operator[] Should take in an int and return arr at that index if it is a valid index notEqual The notEqual should take in another myArray object and return true if the objects are not equal to one another and false if they are equal. operator-(float) Will subtract the float value that is passed in from each of the values in arr Copy constructor Will take...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not loops. You may use JDK String methods like substring() and length(), but do not use the JDK methods to avoid coding the algorithms assigned. For example, don't use String.reverse(). public boolean recursiveContains(char c, String s) returns true if the String contains the char, otherwise returns false. Here is the code for this method, which you should use as an example to see how to...
Python: Create two Binary Tree class methods that can return the maximum value within a Binary...
Python: Create two Binary Tree class methods that can return the maximum value within a Binary Tree and the minimum value within a Binary Tree. Test the methods in your code Example syntax to call these methods: MyTree.Max() MyTree.Min()
Language: Java I have written this code but not all methods are running. First method is...
Language: Java I have written this code but not all methods are running. First method is running fine but when I enter the file path, it is not reading it. Directions The input file must be read into an input array and data validated from the array. Input file format (500 records maximum per file): comma delimited text, should contain 6 fields: any row containing exactly 6 fields is considered to be invalid Purpose of this code is to :...
In this project you will implement the DataFrame class along with the all the methods that...
In this project you will implement the DataFrame class along with the all the methods that are represented in the class definition. DataFrame is a table with rows and columns – columns and rows have names associated with them also. For this project we will assume that all the values that are stored in the columns and rows are integers. After you have tested your class, you have to execute the main program that is also given below. DataFrame Class...
Using Java Write the class RecursiveProbs, with the methods listed below. Write all the methods using...
Using Java Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, NOT LOOPS. You may use JDK String Methods like substring() and length(), but do not use the JDK methods to avoid coding algorithms assigned. For example, don’t use String.revers(). public boolean recursiveContains(char c, String s) { if (s.length() == 0) return false; if (s.charAt(s.length() - 1) == c) return true; else return recursiveContains(c, s.substring(0, s.length() - 1)); } public boolean recursiveAllCharactersSame(String s) return...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT