Skip to main content

Accept prefix expressions, and construct a Binary tree and perform recursive and non-recursive traversal.

CODE:


#include <iostream>

#include <stack>

#include <cctype>

using namespace std;

struct Node {

char data;

Node* left;

Node* right;

Node(char value) : data(value), left(nullptr), right(nullptr) {}

};

bool isOperand(char c) {

return isalnum(c);

}

Node* constructTree(string prefix) {

stack<Node*> st;

for (int i = prefix.length() - 1; i >= 0; i--) {

char c = prefix[i];

if (isOperand(c))

{

st.push(new Node(c));

}

else

{

Node* operand1 = st.top(); st.pop();

Node* operand2 = st.top(); st.pop();

Node* newNode = new Node(c);

newNode->left = operand1;


newNode->right = operand2;

st.push(newNode);

}

}

return st.top();

}

void inorderTraversal(Node* root) {

if (root) {

inorderTraversal(root->left);

cout << root->data << " ";

inorderTraversal(root->right);

}

}

int main()

{

string prefixExpression;

cout << "Enter the prefix expression: ";

cin >> prefixExpression;

Node* root = constructTree(prefixExpression);

cout << "Inorder Traversal: ";

inorderTraversal(root);

return 0;

}










Popular posts from this blog

Write a program to create a class Student2 along with two method getData (), printData () to get the value through argument and display the data in printData. Create the two objects s1, s2 to declare and access the values from class STtest.

 CODE: import java.util.Scanner; class Student2 {     private String name;     private int age;          // Method to set data     public void getData(String name, int age) {         this.name = name;         this.age = age;     }          // Method to print data     public void printData() {         System.out.println("Name: " + name);         System.out.println("Age: " + age);     } } public class STtest {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);                  // Creating objects of Student2 class         Student2 s1 = new Student2();         Student2 s2 = new Student2();              ...