Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Upda.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
Please write in C++ and should be able to compile and debug.Thank you
Create a class called BinaryTreeDeque. This binary tree implements all of the functionality of
the BinaryTree class, but instead of storing its values in a tree structure, the element values are
stored in a deque, using pointers to maintain the relationship between the binary tree and its node
values. Additionally: deque * getValues() - returns a copy of the deque the current array of
values (which should be in insertion order).
Solution
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Code :-
-------------------------
binarytreedequeue.h
#ifndef BINARYTREEDEQUE_H
#define BINARYTREEDEQUE_H
// Program for linked implementation of complete binary tree
#include
#include
// For Queue Size
#define SIZE 50
// A tree node
struct node
{
int data;
struct node *right,*left;
};
// A queue node
struct Queue
{
int front, rear;
int size;
struct node* *array;
};
class BinaryTreeDeque
{
public:
BinaryTreeDeque();
struct node* newNode(int data);
struct Queue* createQueue(int size);
int isEmpty(struct Queue* queue);
int isFull(struct Queue* queue);
int hasOnlyOneItem(struct Queue* queue);
void Enqueue(struct node *root, struct Queue* queue);
struct node* Dequeue(struct Queue* queue);
struct node* getFront(struct Queue* queue);
int hasBothChild(struct node* temp);
void insert(struct node **root, int data, struct Queue* queue);
void display(struct Queue* queue);
node * getValues(struct Queue* queue);
};
#endif // BINARYTREEDEQUE_H
binarydequeue.cpp
---------------------------------------
#include \"binarytreedeque.h\"
BinaryTreeDeque::BinaryTreeDeque()
{
}
// A utility function to create a new tree node
struct node* BinaryTreeDeque::newNode(int data)
{
struct node* temp = (struct node*) malloc(sizeof( struct node ));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to create a new Queue
struct Queue* BinaryTreeDeque::createQueue(int size)
{
struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue ));
queue->front = queue->rear = -1;
queue->size = size;
queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;
return queue;
}
// Standard Queue Functions
int BinaryTreeDeque::isEmpty(struct Queue* queue)
{
return queue->front == -1;
}
int BinaryTreeDeque::isFull(struct Queue* queue)
{ return queue->rear == queue->size - 1; }
int BinaryTreeDeque::hasOnlyOneItem(struct Queue* queue)
{ return queue->front == queue->rear; }
void BinaryTreeDeque::Enqueue(struct node *root, s.
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
This document contains Java code that defines a binary tree class with methods for inserting nodes, searching for values, counting nodes, checking if the tree is empty, and traversing the tree in preorder, inorder and postorder manners. A main method is included that allows a user to test the binary tree operations by selecting options from a menu to insert nodes, search, count nodes or check emptiness and displays the results of tree traversals.
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
MAIN.CPP
#include <iostream>
#include <string>
using namespace std;
#include "bstree.h"
// Prints a single string, used by FSTree::inorder to print all
// values in the tree in correct order.
void print_string (string s) { cout << s << endl; }
// Prints a single string preceeded by a number of hyphens, used by
// BSTree::preorder to print a visual representation of the tree.
void print_string_depth (string s, int n) {
for (int i = 0; i < n; i++)
cout << '-';
cout << s << endl;
}
int main () {
// Create a binary search tree.
BSTree<string> t;
// Insert some strings for testing.
t.insert("dog");
t.insert("bird");
t.insert("cat");
t.insert("turtle");
t.insert("giraffe");
t.insert("snake");
t.insert("deer");
t.insert("groundhog");
t.insert("horse");
// Output the values stored in the tree.
cout << "Values stored in the tree are:n";
t.inorder(print_string);
cout << "n";
cout << "The structure of the tree is as follows:n";
t.preorder(print_string_depth);
cout << "n";
}
BSTREE.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left.
The document contains C program code to implement three data structures using linked lists:
1) A stack using a singly linked list with push, pop, and display functions.
2) A queue using a singly linked list with enqueue, dequeue, and display functions.
3) A program to merge two sorted linked lists by comparing nodes and appending to the merged list.
Pseudocode and sample test cases are provided for each problem.
The document discusses tree data structures and binary trees. It provides definitions for key tree terminology like root, child, parent, leaf nodes, and discusses tree traversal methods like preorder, inorder, and postorder traversal. It also covers implementing binary trees using linked lists and building binary search trees with functions for insertion, searching, and deletion of nodes.
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Upda.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
Please write in C++ and should be able to compile and debug.Thank you
Create a class called BinaryTreeDeque. This binary tree implements all of the functionality of
the BinaryTree class, but instead of storing its values in a tree structure, the element values are
stored in a deque, using pointers to maintain the relationship between the binary tree and its node
values. Additionally: deque * getValues() - returns a copy of the deque the current array of
values (which should be in insertion order).
Solution
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Code :-
-------------------------
binarytreedequeue.h
#ifndef BINARYTREEDEQUE_H
#define BINARYTREEDEQUE_H
// Program for linked implementation of complete binary tree
#include
#include
// For Queue Size
#define SIZE 50
// A tree node
struct node
{
int data;
struct node *right,*left;
};
// A queue node
struct Queue
{
int front, rear;
int size;
struct node* *array;
};
class BinaryTreeDeque
{
public:
BinaryTreeDeque();
struct node* newNode(int data);
struct Queue* createQueue(int size);
int isEmpty(struct Queue* queue);
int isFull(struct Queue* queue);
int hasOnlyOneItem(struct Queue* queue);
void Enqueue(struct node *root, struct Queue* queue);
struct node* Dequeue(struct Queue* queue);
struct node* getFront(struct Queue* queue);
int hasBothChild(struct node* temp);
void insert(struct node **root, int data, struct Queue* queue);
void display(struct Queue* queue);
node * getValues(struct Queue* queue);
};
#endif // BINARYTREEDEQUE_H
binarydequeue.cpp
---------------------------------------
#include \"binarytreedeque.h\"
BinaryTreeDeque::BinaryTreeDeque()
{
}
// A utility function to create a new tree node
struct node* BinaryTreeDeque::newNode(int data)
{
struct node* temp = (struct node*) malloc(sizeof( struct node ));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to create a new Queue
struct Queue* BinaryTreeDeque::createQueue(int size)
{
struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue ));
queue->front = queue->rear = -1;
queue->size = size;
queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;
return queue;
}
// Standard Queue Functions
int BinaryTreeDeque::isEmpty(struct Queue* queue)
{
return queue->front == -1;
}
int BinaryTreeDeque::isFull(struct Queue* queue)
{ return queue->rear == queue->size - 1; }
int BinaryTreeDeque::hasOnlyOneItem(struct Queue* queue)
{ return queue->front == queue->rear; }
void BinaryTreeDeque::Enqueue(struct node *root, s.
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
This document contains Java code that defines a binary tree class with methods for inserting nodes, searching for values, counting nodes, checking if the tree is empty, and traversing the tree in preorder, inorder and postorder manners. A main method is included that allows a user to test the binary tree operations by selecting options from a menu to insert nodes, search, count nodes or check emptiness and displays the results of tree traversals.
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
MAIN.CPP
#include <iostream>
#include <string>
using namespace std;
#include "bstree.h"
// Prints a single string, used by FSTree::inorder to print all
// values in the tree in correct order.
void print_string (string s) { cout << s << endl; }
// Prints a single string preceeded by a number of hyphens, used by
// BSTree::preorder to print a visual representation of the tree.
void print_string_depth (string s, int n) {
for (int i = 0; i < n; i++)
cout << '-';
cout << s << endl;
}
int main () {
// Create a binary search tree.
BSTree<string> t;
// Insert some strings for testing.
t.insert("dog");
t.insert("bird");
t.insert("cat");
t.insert("turtle");
t.insert("giraffe");
t.insert("snake");
t.insert("deer");
t.insert("groundhog");
t.insert("horse");
// Output the values stored in the tree.
cout << "Values stored in the tree are:n";
t.inorder(print_string);
cout << "n";
cout << "The structure of the tree is as follows:n";
t.preorder(print_string_depth);
cout << "n";
}
BSTREE.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left.
The document contains C program code to implement three data structures using linked lists:
1) A stack using a singly linked list with push, pop, and display functions.
2) A queue using a singly linked list with enqueue, dequeue, and display functions.
3) A program to merge two sorted linked lists by comparing nodes and appending to the merged list.
Pseudocode and sample test cases are provided for each problem.
The document discusses tree data structures and binary trees. It provides definitions for key tree terminology like root, child, parent, leaf nodes, and discusses tree traversal methods like preorder, inorder, and postorder traversal. It also covers implementing binary trees using linked lists and building binary search trees with functions for insertion, searching, and deletion of nodes.
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
The program implements a binary search tree to store 20 integers input by the user. It performs level order, preorder, inorder and postorder traversals of the tree, printing the value and level of each node. It also outputs the number of leaf nodes, nodes with one child, and nodes with two children. Finally, it calculates and prints the maximum and minimum leaf levels and checks if the tree is balanced.
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
This document provides an overview of various topics related to computer science including: CS50 IDE, check50, debug50, help50, printf, style50, valgrind, ddb50, strings, characters, pointers, structures, arrays, linked lists, trees, hash tables, tries, and binary search trees. Code examples are provided for swapping variables, allocating memory, defining a student struct, creating a binary search tree, and searching a binary search tree. References are included to online resources for further information on data structures.
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
A)
B)
// C++ program to create a Complete Binary tree from its Linked List
// Representation
#include
#include
#include
using namespace std;
// Linked list node
struct ListNode
{
int data;
ListNode* next;
};
// Binary tree node structure
struct BinaryTreeNode
{
int data;
BinaryTreeNode *left, *right;
};
// Function to insert a node at the beginning of the Linked List
void push(struct ListNode** head_ref, int new_data)
{
// allocate node and assign data
struct ListNode* new_node = new ListNode;
new_node->data = new_data;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
}
// method to create a new binary tree node from the given data
BinaryTreeNode* newBinaryTreeNode(int data)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// converts a given linked list representing a complete binary tree into the
// linked representation of binary tree.
void convertList2Binary(ListNode *head, BinaryTreeNode* &root)
{
// queue to store the parent nodes
queue q;
// Base Case
if (head == NULL)
{
root = NULL; // Note that root is passed by reference
return;
}
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// 2.a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// 2.c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
q.push(leftChild);
head = head->next;
if (head)
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// 2.b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
{
if (root)
{
inorderTraversal( root->left );
cout << root->data << \" \";
inorderTraversal( root->right );
}
}
// Driver program to test above functions
int main()
{
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << \"Inorder Traversal of the constructed Binary Tree is: \ \";
inorderTraversal(root);
return 0;
}
c)
#include
#include
using namespace std;
template
class bintree
{
bintree *left;
T data;
bintree *right;
public :
bintree()
{
left=right=NULL;
}
void create();
void preorder();
void inorder();
void pos.
For this project, write a program that stores integers in a binary.docxbudbarber38650
For this project, write a program that stores integers in a binary search tree.
The tree should use the BTNode class which is provided.
Write a test program that generates 20 random numbers in the range of -50 to 50 to build the tree and then uses preorderPrint,
inorderPrint, and postOrderPrint to display the contents of the tree.
To get an A implement a new method for the BTNode class which creates a Java vector class to contain
the data from all the nodes in the tree. The specification for this method is provided in the BTNode file.
Details about the Java vector class are provided in Appendix D, although the only vector method you'll use is addElement.
Also specify and implement in-order and post-order traversals and answer the question which of the
three new methods creates a vector with the entries sorted from smallest to largest?
Your test program should display the vectors created by your new methods rather than the print methods of BTNode.
// File: BTNode.java from the package edu.colorado.nodes
// Complete documentation is available from the BTNode link in:
// http://www.cs.colorado.edu/~main/docs/
package BTNode;
import java.util.Vector;
/******************************************************************************
* A <CODE>BTNode<<E></CODE> provides a node for a binary tree. Each node
* contains a piece of data (which is a reference to an E object) and references
* to a left and right child. The references to children may be null to indicate
* that there is no child. The reference stored in a node can also be null.
*
* <dl><dt><b>Limitations:</b> <dd>
* Beyond <CODE>Int.MAX_VALUE</CODE> elements, <CODE>treeSize</CODE>, is
* wrong.
*
* <dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../../../../edu/colorado/nodes/BTNode.java">
* http://www.cs.colorado.edu/~main/edu/colorado/nodes/BTNode.java </A>
*
* @author Michael Main
* <A HREF="mailto:[email protected]"> ([email protected]) </A>
*
* @version
* Jul 22, 2005
******************************************************************************/
public class BTNode<E>
{
// Invariant of the BTNode<E> class:
// 1. Each node has one reference to an E Object, stored in the instance
// variable data.
// 2. The instance variables left and right are references to the node's
// left and right children.
private E data;
private BTNode<E> left, right;
/**
* Initialize a <CODE>BTNode</CODE> with a specified initial data and links
* children. Note that a child link may be the null reference,
* which indicates that the new node does not have that child.
* @param <CODE>initialData</CODE>
* the initial data of this new node
* @param <CODE>initialLeft</CODE>
* a reference to the left child of this new node--this reference may be null
* to indicate that there is no node after this new node.
* @param <CODE>initialRight</CODE>
.
This document contains information about trees and binary trees. It begins with definitions of trees, tree terminology like root, child, parent and traversals like preorder, inorder and postorder. It then discusses properties of binary trees like complete and full binary trees. Various representations of trees like linked and sequential representations are described. Finally, it provides examples of using trees to represent expressions and evaluating them using traversals.
This document discusses binary trees and tree traversal algorithms. It begins with definitions of trees and binary trees. It then covers tree traversal methods including preorder, inorder, postorder and level order traversal. Implementation of these traversals using recursion is shown. Applications to arithmetic expressions and propositional logic are discussed. Node structures for representing binary trees and evaluating expressions are also presented.
This document discusses binary trees and binary search trees in C++. It includes functions to create and traverse binary trees in preorder, inorder, and postorder fashion. For binary search trees, it includes functions to insert nodes, perform inorder traversal, find the minimum value node, and delete nodes. These data structures and functions provide ways to organize and manipulate tree-based data in C++ programs.
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
The document discusses various operations on linked lists and arrays in C language like creation, traversal, insertion, deletion etc. It includes code snippets to implement array as an abstract data type, linear and binary search on arrays, creation and traversal of singly linked lists, different ways to insert and delete nodes from linked lists, operations on circular linked lists and basics of doubly linked lists.
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdfarihantmobileselepun
(1)Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. I of
BST have the same data from each input record.
Download traversal-lab.pptx, inventory.txt, BinNode.java, BSTNode.java, BST.java,
Dictionary.java .
Perform specifications as follow:
(a)Provide Add, Delete and Retrieve functions for user to access the database. Reject duplicate
record when add a new record.
(b)Modify BST.java to add printpostOrder, printpreOrder methods.
(c)At the end, display inorder, postorder and preorder of the tree.
Codes:
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** ADT for binary tree nodes */
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
//********************************************************************
// StringTree.java
//
//********************************************************************
import java.util.*;
public class StringTree
{
private Node root;
//----------------------------------------------------------------
// Creates an initially empty tree.
//----------------------------------------------------------------
public StringTree()
{
root = null;
}
//----------------------------------------------------------------
// Adds a string to the tree.
//----------------------------------------------------------------
public void addString (String str)
{
root = addStringToSubTree(str, root);
}
//----------------------------------------------------------------
// Adds a string to the subtree with the given root node
//----------------------------------------------------------------
private Node addStringToSubTree (String str, Node node)
{
Node result = node;
if (node == null)
result = new Node(str);
// If the new string comes before the string in the node, add
// the new string to the left child. Otherwise, add it to the
// right child.
else
if (str.compareTo(node.value) < 0)
node.left = addStringToSubTree(str, node.left);
else
node.right = addStringToSubTree(str, node.right);
return result;
}
//----------------------------------------------------------------
// Prints the result of a depth-first traversal of the tree using
// recursion.
//----------------------------------------------------------------
public void traverseWithRecursion()
{
traverseWithRecursion(root);
}
//----------------------------------------------------------------
// Prints the elements in the specified tree using recursion.
//----------------------------------------------------------------
private void traverseWithRecursion (Node node)
{
if (node != null)
{
traverseWithRecursion (node.left);
System.
Help to implement delete_node get_succ get_pred walk and.pdfcontact32
Help to implement delete_node, get_succ, get_pred, walk, and tree_search in the script
following the given structure:
#include "bst.h"
// ---------------------------------------
// Node class
// Default constructor
Node::Node() {
// TODO: Implement this
key = 0;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Constructor
Node::Node(int in) {
// TODO: Implement this
key = in;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Destructor
Node::~Node() {
// TODO: Implement this
delete left;
delete right;
}
// Add parent
void Node::add_parent(Node* in) {
// TODO: Implement this
parent = in;
}
// Add to left of current node
void Node::add_left(Node* in) {
// TODO: Implement this
left = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Add to right of current node
void Node::add_right(Node* in) {
// TODO: Implement this
right = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Get key
int Node::get_key()
{
// TODO: Implement this
return key;
}
// Get parent node
Node* Node::get_parent()
{
// TODO: Implement this
return parent;
}
// Get left node
Node* Node::get_left()
{
// TODO: Implement this
return left;
}
// Get right node
Node* Node::get_right()
{
// TODO: Implement this
return right;
}
// Print the key to ostream to
// Do not change this
void Node::print_info(ostream& to)
{
to << key << endl;
}
// ---------------------------------------
// ---------------------------------------
// BST class
// Walk the subtree from the given node
void BST::inorder_walk(Node* in, ostream& to)
{
// TODO: Implement this
if (in != nullptr) {
inorder_walk(in->get_left(), to);
in->print_info(to);
inorder_walk(in->get_right(), to);
}
}
// Constructor
BST::BST()
{
// TODO: Implement this
root = nullptr;
}
// Destructor
BST::~BST()
{
// TODO: Implement this
delete root;
}
// Insert a node to the subtree
void BST::insert_node(Node* in)
{
// TODO: Implement this
Node* curr = root;
Node* par = nullptr;
while (curr != nullptr) {
par = curr;
if (in->get_key() < curr->get_key()) {
curr = curr->get_left();
} else {
curr = curr->get_right();
}
}
in->add_parent(par);
if (par == nullptr) {
root = in;
} else if (in->get_key() < par->get_key()) {
par->add_left(in);
} else {
par->add_right(in);
}
}
// Delete a node to the subtree
void BST::delete_node(Node* out)
{
// TODO: Implement this
}
// minimum key in the BST
Node* BST::tree_min()
{
// TODO: Implement this
return get_min(root);
}
// maximum key in the BST
Node* BST::tree_max()
{
// TODO: Implement this
return get_max(root);
}
// Get the minimum node from the subtree of given node
Node* BST::get_min(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_left() != nullptr) {
in = in->get_left();
}
return in;
}
// Get the maximum node from the subtree of given node
Node* BST::get_max(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_right() != nullptr) {
in = in->get_right();
}
return in;
}
// Get successor of the given node
Node* BS.
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
The document discusses various C++ constructors including default constructors, initialization lists, copy constructors, assignment operators, and destructors. It provides examples of how to properly implement these special member functions to avoid problems like shallow copying and double deletes.
I have C++ question that I do not know how to do, Can you teach me t.pdffasttrackscardecors
I have C++ question that I do not know how to do, Can you teach me this question:
Draw a CLASS diagram for Binary Search Tree (BTS) :
can you explain me each step, thank you
Solution
//program to convert Binary Tree to Binary Search Tree
#include
#include
// A binary tree node structure
struct node
{
int data;
struct node *left;
struct node *right;
};
void storeInorder (struct node* node, int inorder[], int *index_ptr)
{
// Base Case
if (node == NULL)
return;
// first store the left subtree
storeInorder (node->left, inorder, index_ptr);
// Copy the root\'s data
inorder[*index_ptr] = node->data;
(*index_ptr)++; // increase index for next entry
// finally store the right subtree
storeInorder (node->right, inorder, index_ptr);
}
/* A helper function to count nodes in a Binary Tree */
int countNodes (struct node* root)
{
if (root == NULL)
return 0;
return countNodes (root->left) +
countNodes (root->right) + 1;
}
// Following function is needed for library function qsort()
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
/* A helper function that copies contents of arr[] to Binary Tree.
This functon basically does Inorder traversal of Binary Tree and
one by one copy arr[] elements to Binary Tree nodes */
void arrayToBST (int *arr, struct node* root, int *index_ptr)
{
// Base Case
if (root == NULL)
return;
/* first update the left subtree */
arrayToBST (arr, root->left, index_ptr);
/* Now update root\'s data and increment index */
root->data = arr[*index_ptr];
(*index_ptr)++;
/* finally update the right subtree */
arrayToBST (arr, root->right, index_ptr);
}
// This function converts a given Binary Tree to BST
void binaryTreeToBST (struct node *root)
{
// base case: tree is empty
if(root == NULL)
return;
/* Count the number of nodes in Binary Tree so that
we know the size of temporary array to be created */
int n = countNodes (root);
// Create a temp array arr[] and store inorder traversal of tree in arr[]
int *arr = new int[n];
int i = 0;
storeInorder (root, arr, &i);
// Sort the array using library function for quick sort
qsort (arr, n, sizeof(arr[0]), compare);
// Copy array elements back to Binary Tree
i = 0;
arrayToBST (arr, root, &i);
// delete dynamically allocated memory to avoid meory leak
delete [] arr;
}
/* Utility function to create a new Binary Tree node */
struct node* newNode (int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Utility function to print inorder traversal of Binary Tree */
void printInorder (struct node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder (node->left);
/* then print the data of node */
printf(\"%d \", node->data);
/* now recur on right child */
printInorder (node->right);
}
/* Driver function to test above functions */
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure
10
/ \\
30 15
/ \\
20 5 */
root = newNode(10);
root->left = newNode(30.
hi i have to write a java program involving link lists. i have a pro.pdfarchgeetsenterprises
hi i have to write a java program involving link lists. i have a problem with the nodes, as it is
posting errors with the nodes.
please help me with this problem. thank you.
public class LinkLists {
/* only need to store a single pointer to the node at the head
* of the list.
* The pointer is null if the list is empty.
* Also record the size of the list.
*/
protected Node head;
/* invariant: size is the number of nodes in the list pointed to by head */
protected int size;
/* no-arguments default constructor creates an empty list */
public LinkLists() {
head = null; // start with an empty list
size = 0;
}
/* accessor method */
public int size() {
return size;
}
/* value to add to the end of the list
*/
public void add(T value) {
head = addAtEnd(head, value);
size++;
}
/* node of the list to which the value should be added
* value to add to the end of the list
*/
private Node addAtEnd(Node node, T value) {
if (node == null) { // special case
return new Node(value, null);
} else if (node.getNext() == null) { // other special case
node.setNext(new Node(value, null));
} else {
addAtEnd(node.getNext(), value);
}
return node;
}
/* iterative implementation of the same method
* value to add to the end of the list
*/
public void add2(T value) {
if (head == null) {
head = new Node(value, null);
} else {
Node node = head; // guaranteed not to be null initially
while (node.getNext() != null) {
node = node.getNext(); // guaranteed not to be null here
}
// now, node.getNext() is guaranteed to be null
// similar to the second special case in addAtEnd
node.setNext(new Node(value, null));
}
size++;
}
public void remove(int position) throws BadItemCountException {
if ((position < 1) || (position > size)) {
throw new
BadItemCountException(\"invalid position \" + position +
\", only 1..\" + size + \" available\");
}
if (position == 1) {
head = head.getNext();
} else {
Node node = head;
for (int i = 2; i < position; i++) {
node = node.getNext();
}
node.setNext(node.getNext().getNext());
}
size--; // one less item
}
public String toString() {
return toString(head);
}
private String toString(Node node) {
if (node == null) {
return \"\";
} else {
return node.getValue() + \"\ \" + toString(node.getNext());
}
}
public static void main(String[] args) {
/* create two empty lists, make sure they print out correctly */
LinkLists list1 = new LinkLists();
LinkLists list2 = new LinkLists();
System.out.println(\"list1 = \'\" + list1 + \"\', list2 = \'\" + list2 + \"\'\");
System.out.println(\"list1.size() = \" + list1.size() +
\", list2.size() = \" + list2.size());
/* insert some items, keep checking */
list1.add(\"hello\");
list1.add(\"world\");
list2.add(\"foo\");
list2.add(\"bar\");
list2.add(\"baz\");
System.out.println(\"list1 = \'\" + list1 + \"\', list2 = \'\" + list2 + \"\'\");
System.out.println(\"list1.size() = \" + list1.size() +
\", list2.size() = \" + list2.size());
/* remove an item at an invalid position */
boolean caught = false;
try {
list2.remove(4);
} catch .
I need to implment a function that can reverse a single linked list..pdfrohit219406
I need to implment a function that can reverse a single linked list. Not just print it, but actually
change the order of the list.
THIS MUST BE DONE USING RECURSION
EX: a, b, c, d -> d, c, b, a
You have access to the start of the list. Code must be in C++
Solution
#include
using namespace std;
struct node
{
char data;
struct node* next;
};
void reverse(struct node* head)
{
if (head == NULL) //base case
return;
reverse(head->next); //calling function recursively
cout<data<<\",\";
}
//add data to the front of the linked list
void add(struct node** head_ref, char data)
{
//create new node
struct node* newnode=new node();
//adding data
newnode->data = data;
//adding node to the front
newnode->next = (*head_ref);
//making new node head
(*head_ref) = newnode;
}
int main()
{
// create linked list a, b, c, d
struct node* head = NULL;
add(&head, \'d\');
add(&head, \'c\');
add(&head, \'b\');
add(&head, \'a\');
reverse(head);
return 0;
}
//OUTPUT***********
d,c,b,a,
//OUTPUT***********
//This code has been tested on g++ compiler,Please ask in case of any doubt,Thanks..
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
The program implements a binary search tree to store 20 integers input by the user. It performs level order, preorder, inorder and postorder traversals of the tree, printing the value and level of each node. It also outputs the number of leaf nodes, nodes with one child, and nodes with two children. Finally, it calculates and prints the maximum and minimum leaf levels and checks if the tree is balanced.
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
This document provides an overview of various topics related to computer science including: CS50 IDE, check50, debug50, help50, printf, style50, valgrind, ddb50, strings, characters, pointers, structures, arrays, linked lists, trees, hash tables, tries, and binary search trees. Code examples are provided for swapping variables, allocating memory, defining a student struct, creating a binary search tree, and searching a binary search tree. References are included to online resources for further information on data structures.
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
A)
B)
// C++ program to create a Complete Binary tree from its Linked List
// Representation
#include
#include
#include
using namespace std;
// Linked list node
struct ListNode
{
int data;
ListNode* next;
};
// Binary tree node structure
struct BinaryTreeNode
{
int data;
BinaryTreeNode *left, *right;
};
// Function to insert a node at the beginning of the Linked List
void push(struct ListNode** head_ref, int new_data)
{
// allocate node and assign data
struct ListNode* new_node = new ListNode;
new_node->data = new_data;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
}
// method to create a new binary tree node from the given data
BinaryTreeNode* newBinaryTreeNode(int data)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// converts a given linked list representing a complete binary tree into the
// linked representation of binary tree.
void convertList2Binary(ListNode *head, BinaryTreeNode* &root)
{
// queue to store the parent nodes
queue q;
// Base Case
if (head == NULL)
{
root = NULL; // Note that root is passed by reference
return;
}
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// 2.a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// 2.c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
q.push(leftChild);
head = head->next;
if (head)
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// 2.b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
{
if (root)
{
inorderTraversal( root->left );
cout << root->data << \" \";
inorderTraversal( root->right );
}
}
// Driver program to test above functions
int main()
{
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << \"Inorder Traversal of the constructed Binary Tree is: \ \";
inorderTraversal(root);
return 0;
}
c)
#include
#include
using namespace std;
template
class bintree
{
bintree *left;
T data;
bintree *right;
public :
bintree()
{
left=right=NULL;
}
void create();
void preorder();
void inorder();
void pos.
For this project, write a program that stores integers in a binary.docxbudbarber38650
For this project, write a program that stores integers in a binary search tree.
The tree should use the BTNode class which is provided.
Write a test program that generates 20 random numbers in the range of -50 to 50 to build the tree and then uses preorderPrint,
inorderPrint, and postOrderPrint to display the contents of the tree.
To get an A implement a new method for the BTNode class which creates a Java vector class to contain
the data from all the nodes in the tree. The specification for this method is provided in the BTNode file.
Details about the Java vector class are provided in Appendix D, although the only vector method you'll use is addElement.
Also specify and implement in-order and post-order traversals and answer the question which of the
three new methods creates a vector with the entries sorted from smallest to largest?
Your test program should display the vectors created by your new methods rather than the print methods of BTNode.
// File: BTNode.java from the package edu.colorado.nodes
// Complete documentation is available from the BTNode link in:
// http://www.cs.colorado.edu/~main/docs/
package BTNode;
import java.util.Vector;
/******************************************************************************
* A <CODE>BTNode<<E></CODE> provides a node for a binary tree. Each node
* contains a piece of data (which is a reference to an E object) and references
* to a left and right child. The references to children may be null to indicate
* that there is no child. The reference stored in a node can also be null.
*
* <dl><dt><b>Limitations:</b> <dd>
* Beyond <CODE>Int.MAX_VALUE</CODE> elements, <CODE>treeSize</CODE>, is
* wrong.
*
* <dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../../../../edu/colorado/nodes/BTNode.java">
* http://www.cs.colorado.edu/~main/edu/colorado/nodes/BTNode.java </A>
*
* @author Michael Main
* <A HREF="mailto:[email protected]"> ([email protected]) </A>
*
* @version
* Jul 22, 2005
******************************************************************************/
public class BTNode<E>
{
// Invariant of the BTNode<E> class:
// 1. Each node has one reference to an E Object, stored in the instance
// variable data.
// 2. The instance variables left and right are references to the node's
// left and right children.
private E data;
private BTNode<E> left, right;
/**
* Initialize a <CODE>BTNode</CODE> with a specified initial data and links
* children. Note that a child link may be the null reference,
* which indicates that the new node does not have that child.
* @param <CODE>initialData</CODE>
* the initial data of this new node
* @param <CODE>initialLeft</CODE>
* a reference to the left child of this new node--this reference may be null
* to indicate that there is no node after this new node.
* @param <CODE>initialRight</CODE>
.
This document contains information about trees and binary trees. It begins with definitions of trees, tree terminology like root, child, parent and traversals like preorder, inorder and postorder. It then discusses properties of binary trees like complete and full binary trees. Various representations of trees like linked and sequential representations are described. Finally, it provides examples of using trees to represent expressions and evaluating them using traversals.
This document discusses binary trees and tree traversal algorithms. It begins with definitions of trees and binary trees. It then covers tree traversal methods including preorder, inorder, postorder and level order traversal. Implementation of these traversals using recursion is shown. Applications to arithmetic expressions and propositional logic are discussed. Node structures for representing binary trees and evaluating expressions are also presented.
This document discusses binary trees and binary search trees in C++. It includes functions to create and traverse binary trees in preorder, inorder, and postorder fashion. For binary search trees, it includes functions to insert nodes, perform inorder traversal, find the minimum value node, and delete nodes. These data structures and functions provide ways to organize and manipulate tree-based data in C++ programs.
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
The document discusses various operations on linked lists and arrays in C language like creation, traversal, insertion, deletion etc. It includes code snippets to implement array as an abstract data type, linear and binary search on arrays, creation and traversal of singly linked lists, different ways to insert and delete nodes from linked lists, operations on circular linked lists and basics of doubly linked lists.
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdfarihantmobileselepun
(1)Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. I of
BST have the same data from each input record.
Download traversal-lab.pptx, inventory.txt, BinNode.java, BSTNode.java, BST.java,
Dictionary.java .
Perform specifications as follow:
(a)Provide Add, Delete and Retrieve functions for user to access the database. Reject duplicate
record when add a new record.
(b)Modify BST.java to add printpostOrder, printpreOrder methods.
(c)At the end, display inorder, postorder and preorder of the tree.
Codes:
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** ADT for binary tree nodes */
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
//********************************************************************
// StringTree.java
//
//********************************************************************
import java.util.*;
public class StringTree
{
private Node root;
//----------------------------------------------------------------
// Creates an initially empty tree.
//----------------------------------------------------------------
public StringTree()
{
root = null;
}
//----------------------------------------------------------------
// Adds a string to the tree.
//----------------------------------------------------------------
public void addString (String str)
{
root = addStringToSubTree(str, root);
}
//----------------------------------------------------------------
// Adds a string to the subtree with the given root node
//----------------------------------------------------------------
private Node addStringToSubTree (String str, Node node)
{
Node result = node;
if (node == null)
result = new Node(str);
// If the new string comes before the string in the node, add
// the new string to the left child. Otherwise, add it to the
// right child.
else
if (str.compareTo(node.value) < 0)
node.left = addStringToSubTree(str, node.left);
else
node.right = addStringToSubTree(str, node.right);
return result;
}
//----------------------------------------------------------------
// Prints the result of a depth-first traversal of the tree using
// recursion.
//----------------------------------------------------------------
public void traverseWithRecursion()
{
traverseWithRecursion(root);
}
//----------------------------------------------------------------
// Prints the elements in the specified tree using recursion.
//----------------------------------------------------------------
private void traverseWithRecursion (Node node)
{
if (node != null)
{
traverseWithRecursion (node.left);
System.
Help to implement delete_node get_succ get_pred walk and.pdfcontact32
Help to implement delete_node, get_succ, get_pred, walk, and tree_search in the script
following the given structure:
#include "bst.h"
// ---------------------------------------
// Node class
// Default constructor
Node::Node() {
// TODO: Implement this
key = 0;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Constructor
Node::Node(int in) {
// TODO: Implement this
key = in;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Destructor
Node::~Node() {
// TODO: Implement this
delete left;
delete right;
}
// Add parent
void Node::add_parent(Node* in) {
// TODO: Implement this
parent = in;
}
// Add to left of current node
void Node::add_left(Node* in) {
// TODO: Implement this
left = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Add to right of current node
void Node::add_right(Node* in) {
// TODO: Implement this
right = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Get key
int Node::get_key()
{
// TODO: Implement this
return key;
}
// Get parent node
Node* Node::get_parent()
{
// TODO: Implement this
return parent;
}
// Get left node
Node* Node::get_left()
{
// TODO: Implement this
return left;
}
// Get right node
Node* Node::get_right()
{
// TODO: Implement this
return right;
}
// Print the key to ostream to
// Do not change this
void Node::print_info(ostream& to)
{
to << key << endl;
}
// ---------------------------------------
// ---------------------------------------
// BST class
// Walk the subtree from the given node
void BST::inorder_walk(Node* in, ostream& to)
{
// TODO: Implement this
if (in != nullptr) {
inorder_walk(in->get_left(), to);
in->print_info(to);
inorder_walk(in->get_right(), to);
}
}
// Constructor
BST::BST()
{
// TODO: Implement this
root = nullptr;
}
// Destructor
BST::~BST()
{
// TODO: Implement this
delete root;
}
// Insert a node to the subtree
void BST::insert_node(Node* in)
{
// TODO: Implement this
Node* curr = root;
Node* par = nullptr;
while (curr != nullptr) {
par = curr;
if (in->get_key() < curr->get_key()) {
curr = curr->get_left();
} else {
curr = curr->get_right();
}
}
in->add_parent(par);
if (par == nullptr) {
root = in;
} else if (in->get_key() < par->get_key()) {
par->add_left(in);
} else {
par->add_right(in);
}
}
// Delete a node to the subtree
void BST::delete_node(Node* out)
{
// TODO: Implement this
}
// minimum key in the BST
Node* BST::tree_min()
{
// TODO: Implement this
return get_min(root);
}
// maximum key in the BST
Node* BST::tree_max()
{
// TODO: Implement this
return get_max(root);
}
// Get the minimum node from the subtree of given node
Node* BST::get_min(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_left() != nullptr) {
in = in->get_left();
}
return in;
}
// Get the maximum node from the subtree of given node
Node* BST::get_max(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_right() != nullptr) {
in = in->get_right();
}
return in;
}
// Get successor of the given node
Node* BS.
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
The document discusses various C++ constructors including default constructors, initialization lists, copy constructors, assignment operators, and destructors. It provides examples of how to properly implement these special member functions to avoid problems like shallow copying and double deletes.
I have C++ question that I do not know how to do, Can you teach me t.pdffasttrackscardecors
I have C++ question that I do not know how to do, Can you teach me this question:
Draw a CLASS diagram for Binary Search Tree (BTS) :
can you explain me each step, thank you
Solution
//program to convert Binary Tree to Binary Search Tree
#include
#include
// A binary tree node structure
struct node
{
int data;
struct node *left;
struct node *right;
};
void storeInorder (struct node* node, int inorder[], int *index_ptr)
{
// Base Case
if (node == NULL)
return;
// first store the left subtree
storeInorder (node->left, inorder, index_ptr);
// Copy the root\'s data
inorder[*index_ptr] = node->data;
(*index_ptr)++; // increase index for next entry
// finally store the right subtree
storeInorder (node->right, inorder, index_ptr);
}
/* A helper function to count nodes in a Binary Tree */
int countNodes (struct node* root)
{
if (root == NULL)
return 0;
return countNodes (root->left) +
countNodes (root->right) + 1;
}
// Following function is needed for library function qsort()
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
/* A helper function that copies contents of arr[] to Binary Tree.
This functon basically does Inorder traversal of Binary Tree and
one by one copy arr[] elements to Binary Tree nodes */
void arrayToBST (int *arr, struct node* root, int *index_ptr)
{
// Base Case
if (root == NULL)
return;
/* first update the left subtree */
arrayToBST (arr, root->left, index_ptr);
/* Now update root\'s data and increment index */
root->data = arr[*index_ptr];
(*index_ptr)++;
/* finally update the right subtree */
arrayToBST (arr, root->right, index_ptr);
}
// This function converts a given Binary Tree to BST
void binaryTreeToBST (struct node *root)
{
// base case: tree is empty
if(root == NULL)
return;
/* Count the number of nodes in Binary Tree so that
we know the size of temporary array to be created */
int n = countNodes (root);
// Create a temp array arr[] and store inorder traversal of tree in arr[]
int *arr = new int[n];
int i = 0;
storeInorder (root, arr, &i);
// Sort the array using library function for quick sort
qsort (arr, n, sizeof(arr[0]), compare);
// Copy array elements back to Binary Tree
i = 0;
arrayToBST (arr, root, &i);
// delete dynamically allocated memory to avoid meory leak
delete [] arr;
}
/* Utility function to create a new Binary Tree node */
struct node* newNode (int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Utility function to print inorder traversal of Binary Tree */
void printInorder (struct node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder (node->left);
/* then print the data of node */
printf(\"%d \", node->data);
/* now recur on right child */
printInorder (node->right);
}
/* Driver function to test above functions */
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure
10
/ \\
30 15
/ \\
20 5 */
root = newNode(10);
root->left = newNode(30.
hi i have to write a java program involving link lists. i have a pro.pdfarchgeetsenterprises
hi i have to write a java program involving link lists. i have a problem with the nodes, as it is
posting errors with the nodes.
please help me with this problem. thank you.
public class LinkLists {
/* only need to store a single pointer to the node at the head
* of the list.
* The pointer is null if the list is empty.
* Also record the size of the list.
*/
protected Node head;
/* invariant: size is the number of nodes in the list pointed to by head */
protected int size;
/* no-arguments default constructor creates an empty list */
public LinkLists() {
head = null; // start with an empty list
size = 0;
}
/* accessor method */
public int size() {
return size;
}
/* value to add to the end of the list
*/
public void add(T value) {
head = addAtEnd(head, value);
size++;
}
/* node of the list to which the value should be added
* value to add to the end of the list
*/
private Node addAtEnd(Node node, T value) {
if (node == null) { // special case
return new Node(value, null);
} else if (node.getNext() == null) { // other special case
node.setNext(new Node(value, null));
} else {
addAtEnd(node.getNext(), value);
}
return node;
}
/* iterative implementation of the same method
* value to add to the end of the list
*/
public void add2(T value) {
if (head == null) {
head = new Node(value, null);
} else {
Node node = head; // guaranteed not to be null initially
while (node.getNext() != null) {
node = node.getNext(); // guaranteed not to be null here
}
// now, node.getNext() is guaranteed to be null
// similar to the second special case in addAtEnd
node.setNext(new Node(value, null));
}
size++;
}
public void remove(int position) throws BadItemCountException {
if ((position < 1) || (position > size)) {
throw new
BadItemCountException(\"invalid position \" + position +
\", only 1..\" + size + \" available\");
}
if (position == 1) {
head = head.getNext();
} else {
Node node = head;
for (int i = 2; i < position; i++) {
node = node.getNext();
}
node.setNext(node.getNext().getNext());
}
size--; // one less item
}
public String toString() {
return toString(head);
}
private String toString(Node node) {
if (node == null) {
return \"\";
} else {
return node.getValue() + \"\ \" + toString(node.getNext());
}
}
public static void main(String[] args) {
/* create two empty lists, make sure they print out correctly */
LinkLists list1 = new LinkLists();
LinkLists list2 = new LinkLists();
System.out.println(\"list1 = \'\" + list1 + \"\', list2 = \'\" + list2 + \"\'\");
System.out.println(\"list1.size() = \" + list1.size() +
\", list2.size() = \" + list2.size());
/* insert some items, keep checking */
list1.add(\"hello\");
list1.add(\"world\");
list2.add(\"foo\");
list2.add(\"bar\");
list2.add(\"baz\");
System.out.println(\"list1 = \'\" + list1 + \"\', list2 = \'\" + list2 + \"\'\");
System.out.println(\"list1.size() = \" + list1.size() +
\", list2.size() = \" + list2.size());
/* remove an item at an invalid position */
boolean caught = false;
try {
list2.remove(4);
} catch .
I need to implment a function that can reverse a single linked list..pdfrohit219406
I need to implment a function that can reverse a single linked list. Not just print it, but actually
change the order of the list.
THIS MUST BE DONE USING RECURSION
EX: a, b, c, d -> d, c, b, a
You have access to the start of the list. Code must be in C++
Solution
#include
using namespace std;
struct node
{
char data;
struct node* next;
};
void reverse(struct node* head)
{
if (head == NULL) //base case
return;
reverse(head->next); //calling function recursively
cout<data<<\",\";
}
//add data to the front of the linked list
void add(struct node** head_ref, char data)
{
//create new node
struct node* newnode=new node();
//adding data
newnode->data = data;
//adding node to the front
newnode->next = (*head_ref);
//making new node head
(*head_ref) = newnode;
}
int main()
{
// create linked list a, b, c, d
struct node* head = NULL;
add(&head, \'d\');
add(&head, \'c\');
add(&head, \'b\');
add(&head, \'a\');
reverse(head);
return 0;
}
//OUTPUT***********
d,c,b,a,
//OUTPUT***********
//This code has been tested on g++ compiler,Please ask in case of any doubt,Thanks..
Similar to Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx (20)
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
1. Data Structure
Lecture No. 14
Binary Expression Tree
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chishti
International Islamic University H-10, Islamabad, Pakistan
Video Lecture
2. Expression trees are binary trees for mathematical expression
Leaves are operands (a, b, c, …)
Other nodes are operators. (+, -, *, /)
This is Expression Tree for
(a+b*c)+((d*e+f)*g)
Binary Expression Tree
+
+
*
b
a
c
*
+ g
f
*
d e
3. Preorder traversal: (node, left, right) gives Prefix Expression.
+ + a * b c * + * d e f g
Expression Tree Traversal
+
+
*
b
a
c
*
+ g
f
*
d e
4. Inorder traversal: (left, node, right) gives Infix Expression.
a + b * c + d * e + f * g
Expression Tree Traversal
+
+
*
b
a
c
*
+ g
f
*
d e
5. Postorder traversal: (left, right, node) gives Postfix Expression.
a b c * + d e * f + g * +
Expression Tree Traversal
+
+
*
b
a
c
*
+ g
f
*
d e
6. Read expression one symbol at a time
If the symbol is an operand
Create a one-node tree
Push its pointer to a stack
If the symbol is an operator
Pop two pointers
Form a new tree whose root is the operator
In the end, the only element of the stack will be the root of an expression tree.
Constructing a Binary Expression Tree from Postfix
7. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
8. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
a
9. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
a b
10. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
11. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c
12. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c d
13. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c d e
14. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
c
e
+
d
15. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
b
+
a
*
c
e
+
d
16. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
*
*
c
e
+
d
b
*
a
17. a b + c d e + * *
Constructing Expression Tree from Postfix
Stack
*
*
c
e
+
d
b
*
a
root
19. #include <iostream>
#include <string>
#include <math.h>
using namespace std;
struct Data{
char opr;
double num;
};
struct Tree_Node {
Tree_Node* left ;
Data data ;
Tree_Node* right ;
};
typedef Tree_Node* SType;
19
Implementation of Binary Expression Tree
struct Node{
SType info ;
Node *next ;
};
class Stack{
private :
Node* head;
public :
Stack( );
bool Is_Empty();
SType Top();
void Push ( SType Data );
SType Pop ( );
~Stack( ) ;
};
Stack::Stack( ){
head = NULL;
}
1 2
20. bool Stack::Is_Empty() {
return head == NULL;
}
SType Stack::Top() {
if ( !Is_Empty() )
return head->info;
return NULL;
}
void Stack :: Push ( SType Data ) {
Node *newNode ;
newNode = new Node ;
if ( newNode == NULL ){
cout << endl << "Stack is full" ;
return;
}
newNode -> info = Data ;
newNode -> next = head ; head = newNode;
}
20
Implementation of Binary Expression Tree
SType Stack :: Pop( ) {
if ( Is_Empty() ){
cout << "Stack is empty " ;
return NULL ;
}
Node *current ;
SType Data ;
current = head ;
Data = current -> info ;
head = head -> next ;
delete current ;
return Data ;
}
Stack :: ~Stack( ){
Node *current ;
while ( head != NULL ){
current = head ;
head = head -> next ; delete head ;
}
}
3 4
22. Binary_Expression_Tree ::
Binary_Expression_Tree(char Postfix[]){
// Traverse through every character of
// input expression
for (int i=0; Postfix[i]; i++) {
// ignore space and tab
if( Postfix[i] == ' ' ||
Postfix[i] == 't')
continue;
// If operand, simply push into stack
if (!Is_Operator(Postfix[i])) {
Data d;
d.num = Postfix[i] - 0x30;
d.opr = 0;
t = New_Tree_Node(d);
St.Push(t);
}
22
Implementation of Binary Expression Tree
else { // operator
Data d;
d.num = 0;
d.opr = Postfix[i];
t = New_Tree_Node(d);
// Pop two top nodes
t1 = St.Pop(); // Remove top
t2 = St.Pop();
// make them children
t->right = t1;
t->left = t2;
// Add this subexpression to stack
St.Push(t);
}
}
// connect it with root pointer
root = St.Pop();
}
7 8
23. double Binary_Expression_Tree ::
Evaluate ( ) {
return Evaluate(root);
}
double Binary_Expression_Tree ::
Evaluate (Tree_Node* node) {
// empty tree
if (node == NULL)
return 0;
// leaf node i.e, an integer
if (node->left == NULL &&
node->right== NULL) {
return node->data.num;
}
23
Implementation of Binary Expression Tree
// Evaluate left subtree
double l_val = Evaluate(node->left);
// Evaluate right subtree
double r_val = Evaluate(node->right);
// Check which operator to apply
if (node->data.opr == '+')
return l_val + r_val;
if (node->data.opr == '-')
return l_val-r_val;
if (node->data.opr == '*')
return l_val*r_val;
if (node->data.opr == '/' )
return l_val/r_val;
if (node->data.opr == '^')
return pow(l_val,r_val);
return 0;
}
9 10