Tree Traversal Coding: How do I code the following in C program?
// ====== BEGIN INSERT FUNCTION DEFS TO WALK TREE =========
// define 3 functions - preorder, inorder, postorder to walk tree, printing out data (char)
// associated with each node visited:
void preorder (node* np) {}
void inorder (node* np) {}
void postorder (node* np) {}
walk.c file with the rest of the code given.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_STRING 200
// ========================== NODE/TREE DEFINITIONS ==========================
// define node structure
typedef struct nd {
int data;
struct nd* left;
struct nd* right;
} node;
// "new" function to create a node, set data value to d and children to NULL
node* newNode(int d) {
node* np;
np = (node*)malloc(sizeof(node));
if (np != NULL) {
np->data = d;
np->left = NULL;
np->right = NULL;
}
return(np);
}
// declare root of our binary tree
node* rootp = NULL;
// ========================== STRING DEFINITIONS ==========================
// dna is a string defining the content and structure of the tree in pre-order with '\n' for NULL pointers
char dna[MAX_STRING] = "ABDHP\n\nQ\n\nIR\n\nS\n\nEJT\n\nU\n\nKV\n\nW\n\nCFL\n\nMX\n\nY\n\nGN\nZ\n\nO\n\n";
// remove the first character from string s and return it, \x01 will be an error code if string is empty
char getFirstChar(char* s) {
char c;
if (strlen(s) > 0) {
// copy the first character
c = s[0];
// remove the first charcter from the string
memmove(s, s+1, strlen(s));
} else {
// empty string, set error code
c = '\x01';
}
return c;
}
// ========================== MAIN RECURSIVE FUNCTION TO BUILD TREE ==========================
// using the instruction in string s, insert the defined nodes into tree pointed to by rp
void insertNode (node* rp, char* s) {
char c; // temporary character
// we assume that rp points to an existing node and
// we are going to add its two children based on the next two instructions in s
if (rp != NULL) {
// if instruction string is not empty then add a new node to the left
if (strlen(s) > 0) {
// get the first character of the string which is our "instruction"
c = getFirstChar(s);
if (c == '\x01') {
printf("ILLEGAL CHARACTER IN INSTRUCTION STRING\n");
}
// if instruction does not tell us to insert null, create a new node and add it as left child, recurse
if (c != '\n') {
rp->left = newNode(c);
insertNode(rp->left, s);
}
}
// if instruction string is not empty then add a new node to the right
if (strlen(s) > 0) {
// get the first character of the string which is our "instruction"
c = getFirstChar(s);
if (c == '\x01') {
printf("ILLEGAL CHARACTER IN INSTRUCTION STRING\n");
}
// if instruction does not tell us to insert null, create a new node and add it as right child, recurse
if (c != '\n') {
rp->right = newNode(c);
insertNode(rp->right, s);
}
}
}
return;
}
// ========================== BEGIN INSERT FUNCTION DEFS TO WALK TREE ==========================
// define 3 functions - preorder, inorder, postorder to walk tree, printing out data (char)
// associated with each node visited:
void preorder (node* np) {}
void inorder (node* np) {}
void postorder (node* np) {}
// ========================== END INSERT FUNCTIONS HERE TO WALK TREE ==========================
// ========================== MAIN PROGRAM ==========================
int main() {
char c; // temporary character variable
// prime the pump - add the first node to the tree and then recursively call on children
rootp = NULL;
// if instruction string is not empty then create root node
if (strlen(dna) > 0) {
// get the first character of the string which is our "instruction"
c = getFirstChar(dna);
if (c == '\x01') {
printf("ILLEGAL CHARACTER IN INSTRUCTION STRING\n");
}
// if instruction does not tell us to insert null, create a new node and add it as left child, recurse
if (c != '\n') {
rootp = newNode(c);
insertNode(rootp, dna);
}
}
// ========================== MAIN PROG CODE TO CALL WALK FUNCTONS ==========================
printf("PREORDER:\n");
preorder(rootp);
printf("\n\n");
printf("INORDER:\n");
inorder(rootp);
printf("\n\n");
printf("POSTORDER:\n");
postorder(rootp);
printf("\n\n");
return 0;
}
Trending nowThis is a popular solution!
Step by stepSolved in 3 steps with 2 images
- C++ Consider the following function as a property of a LinkedBag that contains a Doubly Linked List. Assume a Node has pointers prev and next, which can be read and changed with the standard get and set methods. Assume that the doubly linked list is: 1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6 If you are uncertain what the above diagram depicts, it is a doubly linked list such that: The head of this doubly linked list is the node that contains the value 1. The tail of this doubly linked list is the node that contains the value 6. The 3rd node in this list contains the value 3. The contents of this list are the values 1 through 6 in sequential order. The following questions are regarding the linked list after after the test_function is run. A. The head of the list after the test_function is run contains the value: B. The tail of the list after the test_function is run contains the value: C. The 3rd node in the list after the test_function is run…arrow_forwardData Structure Using C++ (Queue) C++ code (NOT JAVA C++ JUST) C++ PROGRAMMING LANGUAGE PLEASE :: We can use a queue to simulate the flow of customers through a check-out line in a store. In this simulation we will have the following details: one check-out line the expected service time for each customer is one minute (However, they may have to wait in line before being serviced) between zero and two customers join the line every minute We can simulate the flow of customers through the line during a time period n minutes long using the following algorithm: Initialize the queue to empty. for ( minute = 0 ; minute < n ; ++minute ) { if the queue is not empty, then remove the customer at the front of the queue. Compute a random number k between 0 and 3. If k is 1, then add one customer to the line. If k is 2, then add two customers to the line. Otherwise (if k is 0 or 3), do not add any customers to the line. } In addition, the algorithm will keep track…arrow_forwardC++arrow_forward
- Questions: There needs to be a dynamic array of Child that opposes with SCALE and is assigned to "familyTree". The createFamilyTree() function needs to be defined. Please see the C++ code.arrow_forwardProblem DNA: Subsequence markingA common task in dealing with DNA sequences is searching for particular substrings within longer DNA sequences. Write a function mark_dna that takes as parameters a DNA sequence to search, and a shorter target sequence to find within the longer sequence. Have this function return a new altered sequence that is the original sequence with all non-overlapping occurrences of the target surrounded with the characters >> and <<. Hints: ● String slicing is useful for looking at multiple characters at once. ● Remember that you cannot modify the original string directly, you’ll need to build a copy. Start with an empty string and concatenate onto it as you loop. Constraints: ● Don't use the built-in replace string method. All other string methods are permitted. >>> mark_dna('atgcgctagcatg', 'gcg') 'at>>gcg<<ctagcatg' >>> mark_dna('atgcgctagcatg', 'gc')…arrow_forwardC++ Data Structure:Create an AVL Tree C++ class that works similarly to std::map, but does NOT use std::map. In the PRIVATE section, any members or methods may be modified in any way. Standard pointers or unique pointers may be used.** MUST use given Template below: #ifndef avltree_h#define avltree_h #include <memory> template <typename Key, typename Value=Key> class AVL_Tree { public: classNode { private: Key k; Value v; int bf; //balace factor std::unique_ptr<Node> left_, right_; Node(const Key& key) : k(key), bf(0) {} Node(const Key& key, const Value& value) : k(key), v(value), bf(0) {} public: Node *left() { return left_.get(); } Node *right() { return right_.get(); } const Key& key() const { return k; } const Value& value() const { return v; } const int balance_factor() const {…arrow_forward
- Python question Analysis: Invariants (Q16-17) For each of the following functions, identify the loop invariant, exit condition and post condition. Question 16 (Invariant 1) This function returns the list of integers that are multiples of both 3 and 7 that occurs within a given list. Identify the loop exit condition, the loop post-condition, and the loop invariant at the end of the loop, which shows the algorithm’s correctness. def multiples_count(lst): """ Input: a list of integers, lst Output: the list of integers in lst that are multiples of both 3 and 7 """ res = [] for i in range(len(lst)): if lst[i]%3 == 0 and lst[i]%7 == 0: res.append(lst[i]) # Identify the loop invariant here return res Question 17 (Invariant 2) This function checks if a given list (of comparable elements) is sorted in ascending order. Identify the loop exit condition, the loop post-condition, and the loop invariant at the end of each iteration of the loop, which…arrow_forwardCourse: Data Structure and Algorithims Language: Java Kindly make the program in 2 hours. Task is well explained. You have to make the proogram properly in Java: Restriction: Prototype cannot be change you have to make program by using given prototype. TAsk: Create a class Node having two data members int data; Node next; Write the parametrized constructor of the class Node which contain one parameter int value assign this value to data and assign next to null Create class LinkList having one data members of type Node. Node head Write the following function in the LinkList class publicvoidinsertAtLast(int data);//this function add node at the end of the list publicvoid insertAthead(int data);//this function add node at the head of the list publicvoid deleteNode(int key);//this function find a node containing "key" and delete it publicvoid printLinkList();//this function print all the values in the Linklist public LinkListmergeList(LinkList l1,LinkList l2);// this function…arrow_forwardC++ PROGRAM: Please complete my program Implement the 4 functions: bool search(int num), bool insert(int num) , bool remove(int num), bool isEmpty bstree.h #include "tree.h"#include <iostream>using namespace std;class BSTree { BTree* tree; public: BSTree() { tree = new BTree(); } //////////////////////////////////////////////// bool search(int num) { }//////////////////////////////////////////////// bool insert(int num) { // TODO insert }//////////////////////////////////////////////// bool remove(int num) { // TODO remove }/////////////////////////////////////////////// // WARNING. Do not modify this method. void print() { if (isEmpty()) { cout << "EMPTY"; return; } cout << "PRE-ORDER: "; print_preorder(tree->getRoot()); cout << endl << "IN-ORDER: "; print_inorder(tree->getRoot()); cout << endl…arrow_forward
- code in c programarrow_forwardLanguage/Type: C++ binary trees pointers recursion Write a function named hasPath that interacts with a tree of BinaryTreeNode structures representing an unordered binary tree. The function accepts three parameters: a pointer to the root of the tree, and two integers start and end, and returns true if a path can be found in the tree from start down to end. In other words, both start and end must be element data values that are found in the tree, and end must be below start, in one of start's subtrees; otherwise the function returns false. If start and end are the same, you are simply checking whether a single node exists in the tree with that data value. If the tree is empty, your function should return false. For example, suppose a BinaryTreeNode pointer named tree points to the root of a tree storing the following elements. The table below shows the results of several various calls to your function: 67 88 52 1 21 16 99 45 Call Result Reason hasPath(tree, 67, 99) true path exists…arrow_forwardC programming fill in the following code #include "graph.h" #include <stdio.h>#include <stdlib.h> /* initialise an empty graph *//* return pointer to initialised graph */Graph *init_graph(void){} /* release memory for graph */void free_graph(Graph *graph){} /* initialise a vertex *//* return pointer to initialised vertex */Vertex *init_vertex(int id){} /* release memory for initialised vertex */void free_vertex(Vertex *vertex){} /* initialise an edge. *//* return pointer to initialised edge. */Edge *init_edge(void){} /* release memory for initialised edge. */void free_edge(Edge *edge){} /* remove all edges from vertex with id from to vertex with id to from graph. */void remove_edge(Graph *graph, int from, int to){} /* remove all edges from vertex with specified id. */void remove_edges(Graph *graph, int id){} /* output all vertices and edges in graph. *//* each vertex in the graphs should be printed on a new line *//* each vertex should be printed in the following format:…arrow_forward
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY