Question

Code to be written in C++: Initially, you will be given symbols printed in a preorder...

Code to be written in C++:

Initially, you will be given symbols printed in a preorder traversal of a boolean expression tree. The internal nodes of the tree will contain one of the following operators: & (and), | (or), ^ (exclusive-or), or ! (not). The nodes containing the first three operators will have two children, while the nodes containing the ! operator will contain only a left child. The leaves of the tree will contain an operand - either f for false or t for true.

You will then be asked to perform a series of queries, in which, you evaluate the tree, or modification operations in which you change either an operator or an operand.

Input Format

The input begins with two space separated integers, n and q, on a line by itself.  n indicates the number of nodes in the tree, while q gives the number of queries and modification operations.

The next n lines will contain the values from the pre-order traversal of the tree. These will be chosen from the following set of values: {&, |, ^, !, t, f}.

The next q lines will be in one of the following formats:

mod [path] [new_value]

or

eval

where [path] is a string comprised of the symbols 'l' or 'r', and [new_value] is chosen from the following set of values: {&, |, ^, t, f}.

Constraints

1 ≤ n ≤ 104

1 ≤ q ≤ 103

Output Format

For each mod line, you will not output anything, however, you should change the state of the tree, by following the path indicated in the [path] string, and changing the value stored at the node at the end of the path to the value in [new_value]. For example, if the command where mod llr t, you would start at the root, go to the left child (which we will call n1), go to n1's left child (which we will call n2), and then go to n2's right child (which we will call n3). You will then change the value stored at n3 to true.

For each eval line, you should output, on a line by itself, the result obtained when evaluating the current state of the tree, either t or f.

Notes:

  • You should not output anything for the mod lines.

  • There is guaranteed to be a node located at the end of the path specified in the mod commands.

  • After each mod command, you are guaranteed that the tree will remain a valid boolean expression tree. For example, you will never be asked to change a node containing the ! operator, you will never be asked to change the value of a node that contains an operand to an operator, nor will you be asked to change the value of a node that contains an operator to an operand.

Sample Input

6 4
^
!
t
|
f
t
mod ll f
eval
mod r &
eval

Sample Output

f
t

Explanation

Initially the tree looks like the following:

     ^
   /   \
  !     |
 /     / \
t     f   t

After the command mod ll f, the new tree looks like:

     ^
   /   \
  !     |
 /     / \
f     f   t

This corresponds to the boolean expression !f ^ (f | t) = t ^ t = f

Therefore at the eval command we will output f.

After the command mod r &, the new tree looks like:

     ^
   /   \
  !     &
 /     / \
f     f   t

This corresponds to the boolean expression !f ^ (f & t) = t ^ f = t

Therefore at the eval command we will output t.

To get credit you must submit a solution that deserializes the tree using a binary tree node class, and uses this tree to solve the problem.

The nodes must have the following methods, used when appropriate in the solution:

evaluate() that returns true if the subtree rooted at the node evaluates to true, and false otherwise. This method must be implemented recursively.

modify(String path, char newValue) that modifies the subtree by following the path in the first argument to set the node at the end of the path based on newValue. This method must also be implemented recursively.

Here is the code we discussed in class for this assignment:

Code to be written in C++:

class binary_tree_node
{
public:
    typedef char value_type;

    binary_tree_node();

    // Rest of code from lecture
    ...

    bool evaluate();
        
    void modify(string path, char symbol);
   
private:
    value_type data_field;
    binary_tree_node* left_field;
    binary_tree_node* right_field;
}


binary_tree_node::binary_tree_node() {
    cin >> data_field;
    left_field = NULL;
    right_field = NULL;
        
    if (data_field == '^' || data_field == '|' || data_field == '&') {
        left_field = new binary_tree_node();
        right_field = new binary_tree_node();           
    }
    else if (data_field == '!') {
        left_field = new binary_tree_node();            
    }
}


bool binary_tree_node::evaluate() {
    if (data_field == 't') return true;
    if (data_field == 'f') return false;
        
    if (data_field == '!') 
        return !left_field->evaluate();
    if (data_field == '|')
        return left_field->evaluate() || right_field->evaluate();
    // TODO: Finish this!!!
}
        
void binary_tree_node::modify(string path, char symbol){
    if (path == "") {
        data_field = symbol;
        return;
    }
    //TODO: recursive cases
}

int main() {
    int n, m;
    cin >> n >> m;
    binary_tree_node* root = new binary_tree_node();

    for (int i = 0; i < m; i++) {
        string command, path;
        char symbol;
        cin >> command;
        if (command == "eval") {
            // Evaluate the tree and output true or false
        }
        else { // command == "mod"
            cin >> path >> symbol;
            // Change the tree 
        }
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1
*YOUR GIVEN FUNCTIONS HAVE BEEN MODIFIED AND HIGHLIGHTED IN THE CODE WRITTEN BELOW. PLEASE RECTIFY THE SYNTAX ERROR IF ANY*


class binary_tree_node
{
public:
    typedef char value_type;

    binary_tree_node();

    // Rest of code from lecture
    ...

    bool evaluate();
        
    void modify(string path, char symbol);
   
private:
    value_type data_field;
    binary_tree_node* left_field;
    binary_tree_node* right_field;
}


binary_tree_node::binary_tree_node() {
    cin >> data_field;
    left_field = NULL;
    right_field = NULL;
        
    if (data_field == '^' || data_field == '|' || data_field == '&') {
        left_field = new binary_tree_node();
        right_field = new binary_tree_node();           
    }
    else if (data_field == '!') {
        left_field = new binary_tree_node();            
    }
}


bool binary_tree_node::evaluate() {
    if (data_field == 't') return true;
    if (data_field == 'f') return false;
        
    if (data_field == '!') 
        return !left_field->evaluate();
    if (data_field == '|')
        return left_field->evaluate() || right_field->evaluate();
    if (data_field == '&')
        return left_field->evaluate() && right_field->evaluate();
    if (data_field == '^')
        return left_field->evaluate() ^ right_field->evaluate();


}
        
void binary_tree_node::modify(string path, char symbol){
    if (path == "") {
        data_field = symbol;
        return;
    }
    char cur=path[0]
    if(cur=='l')
    {
        left_field->modify(path.substr(1),symbol);
    }
    else
    {
        right_field->modify(path.substr(1),symbol);

    }
    //TODO: recursive cases
}

int main() {
    int n, m;
    cin >> n >> m;
    binary_tree_node* root = new binary_tree_node();

    for (int i = 0; i < m; i++) {
        string command, path;
        char symbol;
        cin >> command;
        if (command == "eval") {
            bool ans=root->evaluate();
            if(ans)
            {
                cout<<"t";
            }
            else
            {
                cout<<"f";
            }
            cout<<endl;

            // Evaluate the tree and output true or false
        }
        else { // command == "mod"
            cin >> path >> symbol;
            root->modify(path,symbol);
            // Change the tree 
        }
    }
}
Add a comment
Know the answer?
Add Answer to:
Code to be written in C++: Initially, you will be given symbols printed in a preorder...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Complete the following code: You are asked to write some functionalities for a spelling checker i...

    Complete the following code: You are asked to write some functionalities for a spelling checker inside Tree.java that has at least the following methods: /*Adds a word to a spelling checker’s collection of correctly spelled words*/ void add(String word) /*Returns true if the given word is spelled correctly*/ boolean check(String word) /*Returns back all words in the tree in alphabetical order*/ public String getDictionaryInAlphabeticalOrder() Store the collection of correctly spelled words in a 26-ary tree. The number 26 indicates that...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

  • 26-ary tree for spell checker in JAVA You are asked to write some functionalities for a...

    26-ary tree for spell checker in JAVA You are asked to write some functionalities for a spelling checker inside Tree.java that has at least the following methods: /*Adds a word to a spelling checker’s collection of correctly spelled words*/ void add(String word) /*Returns true if the given word is spelled correctly*/ boolean check(String word) /*Returns back all words in the tree in alphabetical order*/ public String getDictionaryInAlphabeticalOrder() Store the collection of correctly spelled words in a 26-ary tree. The number...

  • The original code using the gets() function is written below. You need to do (a) change...

    The original code using the gets() function is written below. You need to do (a) change the provided code so that you now use fgets() function to obtain input from the user instead of gets(), (b) make any other necessary changes in the code because of using fgets() function, and (c) fill in the code for the execute() function so that the whole program works as expected (a simple shell program). Note: part c is already done, and the execute...

  • C++ Help with Test #1 (at bottom) to work properly. May adjust code to work or...

    C++ Help with Test #1 (at bottom) to work properly. May adjust code to work or add any additional code. Do not use global variables. #include <iostream> #include <string> using std::endl; using std::cout; using std::cin; using std::string; void pressAnyKeyToContinue() { printf("Press any key to continue\n"); cin.get(); } //This helps with testing, do not modify. bool checkTest(string testName, int whatItShouldBe, int whatItIs) {    if (whatItShouldBe == whatItIs) { cout << "Passed " << testName << endl; return true; } else...

  • C++ EXERCISE (DATA STRUCTURES). I just need a code for some functions that are missing. Please...

    C++ EXERCISE (DATA STRUCTURES). I just need a code for some functions that are missing. Please help me figure out. Thanks. C++ BST implementation (using a struct) Enter the code below, and then compile and run the program. After the program runs successfully, add the following functions: postorder() This function is similar to the inorder() and preorder() functions, but demonstrates postorder tree traversal. displayParentsWithTwo() This function is similar to the displayParents WithOne() function, but displays nodes having only two children....

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • in c++ please program for this code #include <iostream> #include <fstream> #include <string> #include <cstring> //...

    in c++ please program for this code #include <iostream> #include <fstream> #include <string> #include <cstring> // for string tokenizer and c-style string processing #include <algorithm> // max function #include <stdlib.h> #include <time.h> using namespace std; // Extend the code here as needed class BTNode{ private: int nodeid; int data; int levelNum; BTNode* leftChildPtr; BTNode* rightChildPtr; public: BTNode(){} void setNodeId(int id){ nodeid = id; } int getNodeId(){ return nodeid; } void setData(int d){ data = d; } int getData(){ return data;...

  • Please use the JAVA code attached as an input to the program that must be created...

    Please use the JAVA code attached as an input to the program that must be created IN JAVA. Instructions of the program: java code: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * */ import java.util.Random; public class Rand_Z3_Exp { /** * @param args the command line arguments */ public static void main(String[] args) {...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT