The document provides C code examples for various binary tree operations and traversals including: finding the height/depth and size of a tree, deleting a tree by freeing its nodes, determining if two trees are identical, finding the minimum value in a BST, creating a mirror copy of a tree, computing the maximum depth, returning a pointer to the nth node of an inorder traversal, level order traversal, deleting a node from a BST, searching a BST, counting leaves, and iterative preorder, inorder and postorder traversals. For each operation, the code is presented and discussed.
Arrays allow storing multiple values of the same type. Arrays in C can be declared with the array name, element type, and size. Values can be initialized during or after declaration. Common operations on arrays include sorting, searching, and calculating statistics. Bubble sort iteratively compares and swaps adjacent elements to sort an array in ascending order. Linear search compares each element to a search key, while binary search divides the sorted array in half on each step. Binary search has lower computational complexity of O(log n) compared to O(n) for linear search.
This document discusses binary search trees (BSTs). It describes how BSTs are structured, with each node containing a value greater than all values in its left subtree and less than all values in its right subtree. It then summarizes common BST operations like insertion, deletion, finding minimum/maximum values, and provides pseudocode implementations. The average-case runtime of these operations is analyzed, showing that since the average depth of a BST is O(log N), most operations take O(log N) time on average. Repeated insertions and deletions can cause imbalance and increase the average depth to O(√N).
This document discusses C arrays and how they work. Some key points:
- Arrays in C are really pointers, so array names refer to memory locations rather than variables. Array elements can be accessed and modified using pointer arithmetic.
- Multidimensional arrays lay out elements sequentially in memory in row-major order. Subscripting a multidimensional array uses pointer arithmetic based on the element sizes.
- When arrays are passed to functions, only the pointer is passed by value, not the elements. So functions can modify the caller's array elements through the pointer. The storage order of multidimensional arrays matters for this behavior.
SciPy and NumPy are Python packages that provide scientific computing capabilities. NumPy provides multidimensional array objects and fast linear algebra functions. SciPy builds on NumPy and adds modules for optimization, integration, signal and image processing, and more. Together, NumPy and SciPy give Python powerful data analysis and visualization capabilities. The community contributes to both projects to expand their functionality. Memory mapped arrays in NumPy allow working with large datasets that exceed system memory.
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviEnthought, Inc.
In this webinar, Didrik Pinte provides an introduction to MayaVi, the 3D interactive visualization library for the open source Enthought Tool Suite. These tools provide scientists and engineers a sophisticated Python development framework for analysis and visualization.
Pointers allow programs to store and manipulate memory addresses. A pointer variable contains the address of another variable. Pointers are useful for passing data between functions, returning multiple values from functions, and dynamically allocating memory at runtime. Pointers can also be used to access elements of arrays indirectly and implement multidimensional arrays more efficiently. Pointer notation provides an alternative way to access array elements through pointer arithmetic rather than subscripts.
This document discusses various linear data structures in C including arrays, records, pointers, and related operations. It describes declaring and initializing one-dimensional and two-dimensional arrays. Records are used to store related data elements using structures. Pointer arrays and dynamic arrays allocated at runtime are also covered. Searching algorithms like linear search and binary search, and sorting algorithms like bubble sort are summarized.
Arrays allow storing multiple values of the same type. Arrays in C can be declared with the array name, element type, and size. Values can be initialized during or after declaration. Common operations on arrays include sorting, searching, and calculating statistics. Bubble sort iteratively compares and swaps adjacent elements to sort an array in ascending order. Linear search compares each element to a search key, while binary search divides the sorted array in half on each step. Binary search has lower computational complexity of O(log n) compared to O(n) for linear search.
This document discusses binary search trees (BSTs). It describes how BSTs are structured, with each node containing a value greater than all values in its left subtree and less than all values in its right subtree. It then summarizes common BST operations like insertion, deletion, finding minimum/maximum values, and provides pseudocode implementations. The average-case runtime of these operations is analyzed, showing that since the average depth of a BST is O(log N), most operations take O(log N) time on average. Repeated insertions and deletions can cause imbalance and increase the average depth to O(√N).
This document discusses C arrays and how they work. Some key points:
- Arrays in C are really pointers, so array names refer to memory locations rather than variables. Array elements can be accessed and modified using pointer arithmetic.
- Multidimensional arrays lay out elements sequentially in memory in row-major order. Subscripting a multidimensional array uses pointer arithmetic based on the element sizes.
- When arrays are passed to functions, only the pointer is passed by value, not the elements. So functions can modify the caller's array elements through the pointer. The storage order of multidimensional arrays matters for this behavior.
SciPy and NumPy are Python packages that provide scientific computing capabilities. NumPy provides multidimensional array objects and fast linear algebra functions. SciPy builds on NumPy and adds modules for optimization, integration, signal and image processing, and more. Together, NumPy and SciPy give Python powerful data analysis and visualization capabilities. The community contributes to both projects to expand their functionality. Memory mapped arrays in NumPy allow working with large datasets that exceed system memory.
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviEnthought, Inc.
In this webinar, Didrik Pinte provides an introduction to MayaVi, the 3D interactive visualization library for the open source Enthought Tool Suite. These tools provide scientists and engineers a sophisticated Python development framework for analysis and visualization.
Pointers allow programs to store and manipulate memory addresses. A pointer variable contains the address of another variable. Pointers are useful for passing data between functions, returning multiple values from functions, and dynamically allocating memory at runtime. Pointers can also be used to access elements of arrays indirectly and implement multidimensional arrays more efficiently. Pointer notation provides an alternative way to access array elements through pointer arithmetic rather than subscripts.
This document discusses various linear data structures in C including arrays, records, pointers, and related operations. It describes declaring and initializing one-dimensional and two-dimensional arrays. Records are used to store related data elements using structures. Pointer arrays and dynamic arrays allocated at runtime are also covered. Searching algorithms like linear search and binary search, and sorting algorithms like bubble sort are summarized.
This document discusses disk-based data structures and B-trees. It explains that B-trees allow search trees to be stored on disk by organizing data into pages that are read and written sequentially. The key operations for B-trees are searching, insertion, and deletion. Insertion and deletion may require splitting or merging nodes, distributing keys between nodes, and reading/writing multiple pages. The running time of disk-based algorithms depends on the number of disk accesses and CPU operations rather than just CPU time.
NumPy is a Python library used for working with multidimensional arrays and matrices for scientific computing. It allows fast operations on arrays through optimized C code and is the foundation of the Python scientific computing stack. NumPy arrays can be created in many ways and support operations like indexing, slicing, broadcasting, and universal functions. NumPy provides many useful features for linear algebra, Fourier transforms, random number generation and more.
The document discusses self-referential structures in C. It begins by showing how a struct cannot directly contain a member of its own type, as this would cause infinite recursion. It then demonstrates how to make a struct self-referential by using a pointer to the struct as a member, rather than the struct itself. This allows the compiler to correctly allocate memory for the pointer. Linked lists are provided as an example application of self-referential structures. The document also covers dynamic memory allocation functions like malloc(), calloc(), free() and realloc() in C.
The document discusses stacks and queues. It describes stacks as last-in first-out (LIFO) data structures that support push, pop, peek and isEmpty operations. It provides examples of implementing stacks using arrays and linked lists. It also briefly introduces queues as first-in first-out (FIFO) data structures.
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
This document provides an overview of effective numerical computation in NumPy and SciPy. It discusses how Python can be used for numerical computation tasks like differential equations, simulations, and machine learning. While Python is initially slower than languages like C, libraries like NumPy and SciPy allow Python code to achieve sufficient speed through techniques like broadcasting, indexing, and using sparse matrix representations. The document provides examples of how to efficiently perform tasks like applying functions element-wise to sparse matrices and calculating norms. It also presents a case study for efficiently computing a formula that appears in a machine learning paper using different sparse matrix representations in SciPy.
Here are the function definitions and declarations to transfer the variables and arrays between main and the function as specified:
(a)
float func1(float a, float b, int jstar[20]) {
float x;
// function body
return x;
}
int main() {
float a, b;
int jstar[20];
float x = func1(a, b, jstar);
}
(b)
float func2(int n, char c, double values[50]) {
float x;
// function body
return x;
}
int main() {
int n;
char c;
double values[50
This document provides an overview of the Python programming language. It discusses Python's history and evolution, its key features like being object-oriented, open source, portable, having dynamic typing and built-in types/tools. It also covers Python's use for numeric processing with libraries like NumPy and SciPy. The document explains how to use Python interactively from the command line and as scripts. It describes Python's basic data types like integers, floats, strings, lists, tuples and dictionaries as well as common operations on these types.
Dynamic memory allocation allows programs to dynamically allocate and free memory at runtime rather than having fixed-size arrays. Malloc allocates memory and leaves it uninitialized while calloc allocates and initializes memory to zero. Realloc can change the size of previously allocated memory. Free must be used to release dynamically allocated memory to avoid memory leaks. In C++, new allocates memory and returns a pointer while delete frees memory allocated by new.
Pointers provide a way to indirectly access the location of a data item rather than the value. Pointers can be used to pass arguments by reference between functions and return multiple data items from a function. Pointers also allow arrays to be accessed and manipulated indirectly. Pointers must point to a valid location in memory, and memory must be dynamically allocated for pointers representing arrays. Pointers can be used to represent and manipulate one-dimensional and multi-dimensional arrays.
This document discusses how to implement multi-dimensional arrays in C and describes how they are stored in memory. It explains that a two-dimensional array is stored as a one-dimensional array of rows, with each row being a one-dimensional array stored sequentially in memory. It shows how to access elements of a multi-dimensional array using pointers by treating the array name as a pointer to the first element/row. The document also provides examples using a 2D integer array to demonstrate how to dereference pointers to access elements of the array.
The document discusses dynamic memory allocation in C using functions like malloc(), calloc(), realloc() and free(). It explains that malloc() allocates memory without initializing it, calloc() allocates memory and initializes it to zero, and realloc() resizes previously allocated memory. Examples are provided to demonstrate allocating memory for arrays, 2D arrays, structures and resizing memory. It emphasizes the importance of freeing unneeded memory to avoid memory leaks.
Array
Introduction
One-dimensional array
Multidimensional array
Advantage of Array
Write a C program using arrays that produces the multiplication of two matrices.
NumPy is a Python library that provides multidimensional array and matrix objects to perform scientific computing. It contains efficient functions for operations on arrays like arithmetic, aggregation, copying, indexing, slicing, and reshaping. NumPy arrays have advantages over native Python sequences like fixed size and efficient mathematical operations. Common NumPy operations include elementwise arithmetic, aggregation functions, copying and transposing arrays, changing array shapes, and indexing/slicing arrays.
The document outlines arrays and provides examples of declaring, initializing, and using arrays in C++ programs. It discusses declaring arrays with a specified size and type, initializing arrays using for loops or initializer lists, passing arrays to functions, and searching and sorting array elements. Examples demonstrate initializing arrays, outputting array contents, computing operations on array elements, and using arrays to count outcomes from rolling dice simulations.
The document discusses stacks, queues, and inheritance in C++. It introduces templates for stacks and queues, which allow them to hold different data types. It describes the operations of stacks and queues, including insertion and deletion. It also discusses using inheritance, where a stack is defined as a subtype of a bag, allowing it to inherit bag operations while overriding deletion. An example maze problem is given to illustrate using a stack.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function in C.
An array is a collection of variables of the same type stored in contiguous memory locations that can be accessed using a common name and a single index or subscript. Arrays allow storing and manipulating large number of similar data items efficiently. Some key points about arrays are that they are derived data types, consist of contiguous memory locations, and can store fundamental and user-defined data types.
This document discusses pointers in C programming. It begins by defining pointers as variables that store memory addresses rather than values, and describes some of their applications. It then explains the basic concepts of how variables are stored in memory with unique addresses. The rest of the document provides examples and explanations of pointer declarations, accessing variables through pointers, pointer arithmetic, passing pointers to functions, and other pointer-related topics in C.
Formation à l'école d'architecture de BordeauxXavier COIFFARD
eudi & Vendredi dernier j'étais donc de retour sur Bordeaux pour initier les étudiants en architecture à la plateforme SL. Je leur ai fait une rapide présentation des univers virtuels, de Second Life puis nous sommes rapidement passé à la pratique : comment builder, scripter, terraformer et communiquer
Breadth-first search (BFS) is an algorithm for traversing or searching trees and graphs. It starts at a root node and explores all neighboring nodes at the present depth prior to moving on to the nodes at the next depth level. BFS runs in O(n+m) time on graphs represented with adjacency lists, where it can be used to find connected components, compute spanning forests, and solve other graph problems by labeling edges and vertices during the traversal.
This document discusses disk-based data structures and B-trees. It explains that B-trees allow search trees to be stored on disk by organizing data into pages that are read and written sequentially. The key operations for B-trees are searching, insertion, and deletion. Insertion and deletion may require splitting or merging nodes, distributing keys between nodes, and reading/writing multiple pages. The running time of disk-based algorithms depends on the number of disk accesses and CPU operations rather than just CPU time.
NumPy is a Python library used for working with multidimensional arrays and matrices for scientific computing. It allows fast operations on arrays through optimized C code and is the foundation of the Python scientific computing stack. NumPy arrays can be created in many ways and support operations like indexing, slicing, broadcasting, and universal functions. NumPy provides many useful features for linear algebra, Fourier transforms, random number generation and more.
The document discusses self-referential structures in C. It begins by showing how a struct cannot directly contain a member of its own type, as this would cause infinite recursion. It then demonstrates how to make a struct self-referential by using a pointer to the struct as a member, rather than the struct itself. This allows the compiler to correctly allocate memory for the pointer. Linked lists are provided as an example application of self-referential structures. The document also covers dynamic memory allocation functions like malloc(), calloc(), free() and realloc() in C.
The document discusses stacks and queues. It describes stacks as last-in first-out (LIFO) data structures that support push, pop, peek and isEmpty operations. It provides examples of implementing stacks using arrays and linked lists. It also briefly introduces queues as first-in first-out (FIFO) data structures.
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
This document provides an overview of effective numerical computation in NumPy and SciPy. It discusses how Python can be used for numerical computation tasks like differential equations, simulations, and machine learning. While Python is initially slower than languages like C, libraries like NumPy and SciPy allow Python code to achieve sufficient speed through techniques like broadcasting, indexing, and using sparse matrix representations. The document provides examples of how to efficiently perform tasks like applying functions element-wise to sparse matrices and calculating norms. It also presents a case study for efficiently computing a formula that appears in a machine learning paper using different sparse matrix representations in SciPy.
Here are the function definitions and declarations to transfer the variables and arrays between main and the function as specified:
(a)
float func1(float a, float b, int jstar[20]) {
float x;
// function body
return x;
}
int main() {
float a, b;
int jstar[20];
float x = func1(a, b, jstar);
}
(b)
float func2(int n, char c, double values[50]) {
float x;
// function body
return x;
}
int main() {
int n;
char c;
double values[50
This document provides an overview of the Python programming language. It discusses Python's history and evolution, its key features like being object-oriented, open source, portable, having dynamic typing and built-in types/tools. It also covers Python's use for numeric processing with libraries like NumPy and SciPy. The document explains how to use Python interactively from the command line and as scripts. It describes Python's basic data types like integers, floats, strings, lists, tuples and dictionaries as well as common operations on these types.
Dynamic memory allocation allows programs to dynamically allocate and free memory at runtime rather than having fixed-size arrays. Malloc allocates memory and leaves it uninitialized while calloc allocates and initializes memory to zero. Realloc can change the size of previously allocated memory. Free must be used to release dynamically allocated memory to avoid memory leaks. In C++, new allocates memory and returns a pointer while delete frees memory allocated by new.
Pointers provide a way to indirectly access the location of a data item rather than the value. Pointers can be used to pass arguments by reference between functions and return multiple data items from a function. Pointers also allow arrays to be accessed and manipulated indirectly. Pointers must point to a valid location in memory, and memory must be dynamically allocated for pointers representing arrays. Pointers can be used to represent and manipulate one-dimensional and multi-dimensional arrays.
This document discusses how to implement multi-dimensional arrays in C and describes how they are stored in memory. It explains that a two-dimensional array is stored as a one-dimensional array of rows, with each row being a one-dimensional array stored sequentially in memory. It shows how to access elements of a multi-dimensional array using pointers by treating the array name as a pointer to the first element/row. The document also provides examples using a 2D integer array to demonstrate how to dereference pointers to access elements of the array.
The document discusses dynamic memory allocation in C using functions like malloc(), calloc(), realloc() and free(). It explains that malloc() allocates memory without initializing it, calloc() allocates memory and initializes it to zero, and realloc() resizes previously allocated memory. Examples are provided to demonstrate allocating memory for arrays, 2D arrays, structures and resizing memory. It emphasizes the importance of freeing unneeded memory to avoid memory leaks.
Array
Introduction
One-dimensional array
Multidimensional array
Advantage of Array
Write a C program using arrays that produces the multiplication of two matrices.
NumPy is a Python library that provides multidimensional array and matrix objects to perform scientific computing. It contains efficient functions for operations on arrays like arithmetic, aggregation, copying, indexing, slicing, and reshaping. NumPy arrays have advantages over native Python sequences like fixed size and efficient mathematical operations. Common NumPy operations include elementwise arithmetic, aggregation functions, copying and transposing arrays, changing array shapes, and indexing/slicing arrays.
The document outlines arrays and provides examples of declaring, initializing, and using arrays in C++ programs. It discusses declaring arrays with a specified size and type, initializing arrays using for loops or initializer lists, passing arrays to functions, and searching and sorting array elements. Examples demonstrate initializing arrays, outputting array contents, computing operations on array elements, and using arrays to count outcomes from rolling dice simulations.
The document discusses stacks, queues, and inheritance in C++. It introduces templates for stacks and queues, which allow them to hold different data types. It describes the operations of stacks and queues, including insertion and deletion. It also discusses using inheritance, where a stack is defined as a subtype of a bag, allowing it to inherit bag operations while overriding deletion. An example maze problem is given to illustrate using a stack.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function in C.
An array is a collection of variables of the same type stored in contiguous memory locations that can be accessed using a common name and a single index or subscript. Arrays allow storing and manipulating large number of similar data items efficiently. Some key points about arrays are that they are derived data types, consist of contiguous memory locations, and can store fundamental and user-defined data types.
This document discusses pointers in C programming. It begins by defining pointers as variables that store memory addresses rather than values, and describes some of their applications. It then explains the basic concepts of how variables are stored in memory with unique addresses. The rest of the document provides examples and explanations of pointer declarations, accessing variables through pointers, pointer arithmetic, passing pointers to functions, and other pointer-related topics in C.
Formation à l'école d'architecture de BordeauxXavier COIFFARD
eudi & Vendredi dernier j'étais donc de retour sur Bordeaux pour initier les étudiants en architecture à la plateforme SL. Je leur ai fait une rapide présentation des univers virtuels, de Second Life puis nous sommes rapidement passé à la pratique : comment builder, scripter, terraformer et communiquer
Breadth-first search (BFS) is an algorithm for traversing or searching trees and graphs. It starts at a root node and explores all neighboring nodes at the present depth prior to moving on to the nodes at the next depth level. BFS runs in O(n+m) time on graphs represented with adjacency lists, where it can be used to find connected components, compute spanning forests, and solve other graph problems by labeling edges and vertices during the traversal.
This document describes graph search algorithms like breadth-first search (BFS) and their applications. It provides details on how BFS works, including that it maintains queues to search levels outwards from the starting vertex, and outputs the distance and predecessor of each vertex. BFS runs in O(V+E) time by visiting each vertex and edge once. The document also discusses how BFS can be used to find connected components in a graph and determine if a graph is bipartite.
The document describes the steps of performing a breadth-first search (BFS) on a graph starting from node A. It shows how BFS enqueues nodes onto a FIFO queue as they are discovered and dequeues them to visit their neighbors, marking nodes as discovered along the way. The BFS finishes after all nodes reachable from A have been visited.
1) Trees are hierarchical data structures that store data in nodes connected by edges. They are useful for representing hierarchical relationships.
2) Binary search trees allow quick search, insertion, and deletion of nodes due to the organizational property that the value of each node is greater than all nodes in its left subtree and less than all nodes in its right subtree.
3) Common tree traversal algorithms include preorder, inorder, and postorder traversals, which visit nodes in different orders depending on whether the left/right children or root is visited first.
This document defines and describes trees and graphs as non-linear data structures. It explains that a tree is similar to a linked list but allows nodes to have multiple children rather than just one. The document defines key tree terms like height, ancestors, size, and different types of binary trees including strict, full, and complete. It provides properties of binary trees such as the number of nodes in full and complete binary trees based on height.
A solar tree is a decorative means of producing solar energy and also electricity. It uses multiple no of solar panels which forms the shape of a tree. The panels are arranged in a tree fashion in a tall tower/pole.
TREE stands for
T= TREE GENERATING
R=RENEWABLE
E=ENERGY and
E=ELECTRICITY
This is like a tree in structure and the panels are like leaves of the tree which produces energy.
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
The document provides instructions for augmenting a Binary Search Tree (BST) class to support new operations like returning the nth element, rank of an element, median element, and determining if the tree is perfect or complete. It explains that these operations could be done with in-order traversal but would be inefficient. Instead, each node should store the size of its subtree to guide searches more efficiently. The BST class code is provided to test the augmented operations on.
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.
My C proggram is having trouble in the switch in main. Also the a co.pdfmeerobertsonheyde608
The document contains C code for implementing functions on a binary tree such as insertion, deletion, searching, and traversal. The author notes that their C program is having trouble with the switch statement in main and some tree functions like delete and display. The code implements functions for inserting nodes, finding nodes, deleting nodes, traversing the tree using inorder, preorder and postorder traversal, and calculating the max, min, height, count and sum of nodes. It includes struct definitions for the tree nodes and function prototypes. The main function uses a switch statement to allow the user to select different operations on the tree by entering characters.
#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.
(a)PreOrder, PostOrder and Inorder are three ways you can iterate .pdfANANDSHOE
(a)
PreOrder, PostOrder and Inorder are three ways you can iterate a binary tree. The way these
three are different is in order of root,left child and right child.
Pre Order: root is printed first then lefy child and in last right child.
Given: TreeNode is class which have data part, left child and right child.
TreeNode root is root element of binary tree
Recursive algorithm of Preorder traversal
(A)void printPreorder(TreeNode root)
{
if (root == null) //Exit case if Tree is empty
return;
/* first print data of root because in preorder root is printed first */
System.out.println(root.value ); //recursive calling
/* then recur on left subtree of root*/
printPreorder(root.left); //recursive calling
/* now recur on right subtree of root*/
printPreorder(root.right); //recursive calling
}
Explanation: Here first we check If tree is exist or not. If exist we print root of tree and then
move to left part of current node and apply same process again untill left part is completed. After
that move to right sub tree and do same process again.
(b)
T(n) = T(k) + T(n – k – 1) + c
Where k is the number of nodes on one side of root and n-k-1 on the other side.
Let’s do analysis of boundary conditions
Case 1:left subtree is empty then all the n-1 nodes present in right part only. SO k=0
T(n) = T(0) + T(n-1) + c -(1)
Putting value of T(n-1) in equation 1
T(n) = 2T(0) + T(n-2) + 2c -(2)
Similarly puting value of T(n-3) in equation 2
T(n) = 3T(0) + T(n-3) + 3c
Similarly
T(n) = 4T(0) + T(n-4) + 4c
T(n) = (n-1)T(0) + T(1) + (n-1)c
T(n) = nT(0)-T(0) + (n)c-c
Value of T(0) will be some constant say d.
T(n)= n(d+c)-(c+d)
T(n)=(n-1)(c+d)
T(n) = Theta of n
Case 2: Both left and right subtrees have equal number of nodes.
T(n) = 2T(n/2) + c
which clearly shows T(n)= theta(n)
(c)
void printPreorder(TreeNode root)
{
if (root == null) //Exit case if Tree is empty
return;
/*print left subtree of root*/
printPreorder(root.left); //recursive calling
/* print data of root because in Inorder root is printed in middle */
System.out.println(root.value ); //recursive calling
/* now recur on right subtree of root*/
printPreorder(root.right); //recursive calling
}
(d)
void printPreorder(TreeNode root)
{
if (root == null) //Exit case if Tree is empty
return;
/*print left subtree of root*/
printPreorder(root.left); //recursive calling
/* now recur on right subtree of root*/
printPreorder(root.right); //recursive calling
/* print data of root because in postorder root is printed in last */
System.out.println(root.value ); //recursive calling
}
Solution
(a)
PreOrder, PostOrder and Inorder are three ways you can iterate a binary tree. The way these
three are different is in order of root,left child and right child.
Pre Order: root is printed first then lefy child and in last right child.
Given: TreeNode is class which have data part, left child and right child.
TreeNode root is root element of binary tree
Recursive algorithm of Preorder traversal
(A)void printPreorder(TreeNode root)
{
if .
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.
Here is the code given in the instructionsclass AVL {.pdfmanjan6
Here is the code given in the instructions:
class AVL {
Node root;
private class Node {
int data;
Node left, right;
int height;
private Node(int D, Node L, Node R, int H) {
data=D;
left=L;
right=R;
height=H; // user has to set height
} // of constructor Node
} //of Node
static private void UpdateHeight(Node T) {
if (T ==null) return;
else T.height = Math.max(HEIGHT(T.left),HEIGHT(T.right)) + 1;
} // UPdate Height
static private int HEIGHT(Node T) {
if (T== null ) return(-1);
else return (T.height);
}
// we need to more our right child up
static private Node LeftRotate(Node T) {
System.out.println(\"left rotate with data \" + T.data);
Node Tr;
Tr=T.right; // right child
T.right=Tr.left; // our right child IS NOW hhh
Tr.left=T; // move T down to the left
UpdateHeight(Tr.left); // update the height of T
UpdateHeight(Tr); // update hte height of the new root
return Tr;
} // of LeftRotate
// we move our immediate left node up.
// in doing so, we are now immediat right of our left child
static private Node RightRotate(Node T) {
Node Tl;
System.out.println(\"left rotate with data \" + T.data);
Tl=T.left; // left child
T.left=Tl.right; // our left child is now what our left was pointing to
Tl.right=T; // move T down to the right
UpdateHeight(Tl.right); // update the height of T
UpdateHeight(Tl); // update hte height of the new root
return Tl;
} // of RightRotate
public AVL() {
root=null;
} // of constructor AVL
// method to allow external entity to insert an element into the tree
public void insert(int D)
{
root=insert_internal(D, root);
} // of insert
private Node insert_internal(int D, Node T) {
if (T==null) return( new Node (D, null, null, 0));
if (T.data == D) return T; // the data is already in there
if ( D < T. data ) // go left
{ if (T.left == null)
{
T.left = insert_internal(D,null);
UpdateHeight(T);
}
else { //interior node
T.left = insert_internal(D, T.left);
}
} // of go left
else // D goes to the right
{ if (T.right == null)
{
T.right = insert_internal(D,null);
UpdateHeight(T);
}
else { //interior node
T.right = insert_internal(D, T.right);
}
} // of go right
// now we have to figure out if things are out of
// balance
int diff= HEIGHT(T.right) - HEIGHT(T.left);
System.out.println(\"difference is \" + diff + \" data is \" + T.data);
if ( Math.abs(diff) <= 1) // we are good to go at this level
{
UpdateHeight(T);
return(T);
}
// only if diff is bigger than 1
if ( diff > 1)// right leaning
{ // look at right child and figure out how it is leaning
} // of right leaning
else // left leaning
{ // look at left child to see how it is leaning
Node child = T.left;
int cdiff;
cdiff = HEIGHT(child.right) - HEIGHT(child.left);
System.out.println(\"cdiff is \" + cdiff);
if ( cdiff < 0 ) // left left lean
{ T=RightRotate(T); }
else
{
System.out.println(\"SHAUN\");
preorder_internal(T);
T.left = LeftRotate(T.left);
System.out.println(\"SHAUN\");
preorder_internal(T);
T=RightRotate(T);
}
} // of left leaning
// at this point we have rotated, so we need to.
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
Heap memory is a common pool of dynamic memory used for allocating objects and data structures during program execution. It is part of RAM and allows for longer-lived allocations compared to stack memory. When the heap is full, garbage collection clears unused objects to free up space. Linked lists are linear data structures composed of nodes containing a data field and a pointer to the next node. They allow for dynamic sizes and efficient insertions/deletions unlike arrays. Doubly linked lists include pointers to both the next and previous nodes, allowing traversal in both directions but requiring more space.
Write a C program that reads the words the user types at the command.pdfSANDEEPARIHANT
Write a C program that reads the words the user types at the command prompt (using the \'int
argc, char * argv[] and store each unique letter in a Binary Search Tree. When a duplicate is
encountered do not store the letter again and instead keep track of the count in the tree. Once the
Binary Search tree has been created print out the tree both inorder and reverse order. Also print
the highest and lowest alphabetically letter in the tree if any.
Solution
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void preorder(node *);
findMinimum(struct node* root)
findMaximum(struct node* root)
void reverseLevelOrder(struct node* root)
void main(int argc,char argv) {
char argv = \'N\';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(\"\ Program For Binary Search Tree \");
do {
printf(\"\ 1.Create\");
printf(\"\ 2.Search\");
printf(\"\ 3.Recursive Traversals\");
printf(\"\ 4.Exit\");
printf(\"\ Enter your choice :\");
scanf(\"%d\", &argc);
switch (argc) {
case 1:
do {
new_node = get_node();
printf(\"\ Enter The Element \");
scanf(\"%d\", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf(\"\ Want To enter More Elements?(y/n)\");
argv= getch();
} while (argv == \'y\');
break;
case 2:
if (root == NULL)
printf(\"Tree Is Not Created\");
else {
printf(\"\ The Preorder display : \");
preorder(root);
}
break;
}
} while (argv != 4);
}
/*
Get new Node
*/
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
return newNode(key);
else
insert(root->lchild, new_node);
}
if (new_node->data > root->data) {
if (root->rchild == NULL)
root->rchild = new_node;
return newNode(key);
else
insert(root->rchild, new_node);
}
}
if (key == node->key)
{
(node->count)++;
return node;
}
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf(\"%d\", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
// Returns maximum value in a given Binary Tree
int findMaximum(struct node* root)
{
// Base case
if (root == NULL)
return INT_MAXIMUM;
// Return maximum of 3 values:
// 1) Root\'s data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMaximum (root->lchild);
int rres = findMaximum (root->rchild);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Returns minimum value in a given Binary Tree
int findMinimum(struct node* root)
{
// Base case
if (root == NULL)
return INT_MINIMUM;
// Return minimum of 3 values:
// 1) Root\'s data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMinimum(r.
A data structure is needed to represent a country with cities connected by bidirectional roads. The data structure will allow finding the longest road between any two cities in the country based on query inputs of two cities. A graph data structure using adjacency lists can model the country, with cities as nodes and roads as edges between nodes labeled with their costs. Queries can then find the longest cost path between two cities using graph traversal algorithms.
Write a C++ program that implements a binary search tree (BST) to man.pdfhardjasonoco14599
Write a C++ program that implements a binary search tree (BST) to manage a number of integer
items with different priorities. In order to do so. you will need to maintain a queue as an item in
the tree. Each queue item is an integer. All items in a given queue will have the same priority. As
a new item with a user-specified priority comes in, it should be enqueued in the queue with items
of that priority. A new queue may need to created in case a queue with that priority does not
exist. Use dynamic memory to manage nodes in the queue and BST. Implement the following:
Constructor. Destructor. Overloaded copy constructor. Overloaded assignment operator.
Overloaded \"==\" operator to check if two trees are equal. A tree t1 is equal to t2 if for every
queue in t1, a corresponding queue with the same priority exists in t2 with the same set of
elements (the order of the elements in the queue docs not matter). Overloaded \"
Solution
program using namespace std;
#define width_unit 5
class BStree
{
private:
class Node
{
public:
int data;
Node *left, *right;
Node(int d=0)
:data(d), left(NULL), right(NULL) {}
};
Node *root;
Node * trav(int, Node * &);
void chop(Node * N);
void copy(Node * N);
void print(ostream &, Node *, int) const;
void print(Node *, int) const;
public:
BStree(void);
~BStree(void);
bool find(int);
void insert(int);
void remove(int);
bool empty(void) const;
Tree(const BStree &);
const BStree & operator=(const BStree &);
friend ostream & operator<<(ostream &, const BStree &);
};
BStree::BStree(void)
{
root=NULL;
}
bool Tree::empty(void) const
{
return !root;
}
BStree::Node * BStree::trav(int foo, Node * & par)
{
Node * curr=root;
par=NULL;
while(curr && curr->data != foo)
{
par=curr;
if(foo < curr->data)
curr=curr->left;
else
curr=curr->right;
}
return curr;
}
bool BStree::find(int foo)
{
Node * par=NULL;
Node * curr=trav(foo, par);
return curr;
}
void BStree::insert(int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(!curr)
{
curr= new Node(foo);
if(!par)
root=curr;
else if(foo < par->data)
par->left=curr;
else
par->right=curr;
}
}
void BStree::remove(const int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(curr)
{
if(curr->left && curr->right)
{
Node * tmp=curr;
par=curr;
curr=curr->left;
while(curr->right)
{
par=curr;
curr=curr->right;
}
tmp->data=curr->data;
}
Node *tmp=(curr->left ? curr->left : curr->right);
if(!par)
root=tmp;
else if(par->data < curr->data)
par->right=tmp;
else
par->left=tmp;
delete curr;
}
}
void BStree::chop(Node *N)
{
if(N)
{
chop(N->left);
chop(N->right);
delete N;
}
}
BStree::~BStree(void)
{
chop(root);
}
BStree::BStree(const BStree & T)
{
root=NULL;
copy(T.root);
}
void BStree::copy(Node * N)
{
if(N)
{
insert(N->data);
copy(N->left);
copy(N->right);
}
}
const BStree & BStree::operator=(const BStree & T)
{
if(this != &T)
{
chop(root);
root=NULL;
copy(T.root);
}
return *this;
}
void BStree::print(ostream & ost, Node * curr, int level) const
{
if(curr)
{
print(ost,curr->right,level+1);
ost<data<le.
The document describes code for four sorting algorithms: insertion sort, selection sort, merge sort, and heap sort. For each algorithm, it provides the code, explains the algorithm's approach for sorting an array, and includes a main function that takes user input for an array and prints the sorted output.
Modify this code to do an Insert function for an AVL tree, instead o.pdffathimaoptical
Match the cost behavior that is described with the proper cost type. The unit cost of an item is
$30 per unit when activity is 10,000 units and $15 per unit when activity is 20,000 units. The
total cost of an item is $30,000 when activity is 10,000 units and $30,000 when activity is 20,000
units. The total cost of an item is $30,000 when activity is 10,000 units and $50,000 when
activity is 20,000 units. 1. Variable cost 2. Fixed Cost The unit cost of an item is $30 per unit
when activity is 10,000 units and $20 per unit when activity is 20,000 units 3. Mixed Cost The
total cost of an item is $30,000 when activity is 10,000 units and $60,000 when activity is 20,000
units. The unit cost of an item is $30 per unit when activity is 10,000 units and $30 per unit when
activity is 20,000 units.
Solution
Variable cost is constant or same in per unit but varies in total with change in output
Fixed cost is constant in total but varies in per unit [ that is doesnot change with change in
output]
Mixed cost is neither constant in total nor in per unit
A)Fixed cost ,since same in total [10000*30 = 300000 or 15*20000 = 300000]
B)Fixed cost ,since same in total
C)Mixed cost,neither constant in per unit nor in total
D)Mixed cost ,neither constant in per unit nor in total
E)Variable cost ,constant in per unit [30000/10000 or 60000/20000 = $ 3 per unit]
F)Variable cost .
c).
CS-102 Course_ Binary Tree Lectures .pdfssuser034ce1
Heap sort uses a max heap to sort an array in O(n log n) time. It works by building a max heap from the array and then repeatedly removing the maximum element and placing it in the correct position. It first constructs a max heap from the input array. It then iterates from the end of the array to the beginning, removing each element from the heap and placing it in the current position. This places the largest elements at the end of the array and the smallest at the beginning.
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
The document describes an algorithm to determine if an undirected graph G can be viewed as a perfect left-sided binary tree. It provides BFS and DFS algorithms in pseudocode that take G as input and return true if G is a perfect left-sided binary tree and false otherwise. Both algorithms have a time complexity of O(V+E) where V is the number of vertices and E is the number of edges in G.
A perfect left-sided binary tree is a binary tree where every intern.pdf
Binary Tree
1. Write a C program to find the depth or height of a tree.
Discuss it!
#define max(x,y) ((x)>(y)?(x):(y))
struct Bintree{
int element;
struct Bintree *left;
struct Bintree *right;
};
typedef struct Bintree* Tree;
int height(Tree T)
{
if(!T)
return -1;
else
return (1 + max(height(T->left), height(T->right)))
}
Write a C program to determine the number of elements (or size) in a tree.
Discuss it!
struct Bintree{
int element;
struct Bintree *left;
struct Bintree *right;
};
typedef struct Bintree* Tree;
int CountElements( Tree T )
{
if(!T)
return 0;
else
return (1 + CountElements(T->left) + CountElements(T-
>right));
}
2. Write a C program to delete a tree (i.e, free up its nodes)
Discuss it!
struct Bintree{
int element;
struct Bintree *left;
struct Bintree *right;
};
typedef struct Bintree* Tree;
Tree findMin( Tree T) // Recursively finding min element
{
if( !T )
return NULL;
else if( !T->left )
return T;
else
return findMin( T->left );
}
Tree DeleteTree( int x, Tree T) // To Delete whole tree recursively
{
if(!T)
{
DeleteTree(T->left);
DeleteTree(T->right);
free(T);
}
return NULL;
}
Tree DeleteNode( int x, Tree T ) // To Delete a Node with element x
{
Tree tmp;
if(!T)
return NULL;
else if( x < T->element )
T->left = DeleteNode( x, T->left );
else if( x > T->element )
T->right = DeleteNode( x, T->right );
else if( T->left && T->right )
{
tmp = findMin( T-> right );
T->element = tmp->element;
T->right = DeleteNode( T->element, T->right );
3. }
else
{
tmp = T;
if( T->left )
T = T->left;
else if( T->right )
T = T->right;
free(tmp);
}
}
Write C code to determine if two trees are identical
Discuss it!
struct Bintree{
int element;
struct Bintree *left;
struct Bintree *right;
};
typedef struct Bintree* Tree;
int CheckIdentical( Tree T1, Tree T2 )
{
if(!T1 && !T2) // If both tree are NULL then return true
return 1;
else if((!T1 && T2) || (T1 && !T2)) //If either of one is NULL,
return false
return 0;
else
return ((T1->element == T2->element) && CheckIdentical(T1->left, T2-
i>left)
&& CheckIdentical(T1->right, T2->right));
// if element of both tree are same and left and right tree is also
same then both
trees are same
}
4. Write a C program to find the mininum value in a binary search tree.
Discuss it!
#define NOT_FOUND -999
struct Bintree{
int element;
struct Bintree *left;
struct Bintree *right;
};
typedef struct Bintree* Tree;
int findMinElement( Tree T) // Recursively finding min element
{
if( !T )
return NOT_FOUND;
else if( !T->left )
return T->element;
else
return findMin( T->left );
}
Write a C program to create a mirror copy of a tree (left nodes become right and right
nodes become left)!
Discuss it!
This C code will create a new mirror copy tree.
mynode *copy(mynode *root)
{
mynode *temp;
if(root==NULL)return(NULL);
temp = (mynode *) malloc(sizeof(mynode));
temp->value = root->value;
temp->left = copy(root->right);
temp->right = copy(root->left);
return(temp);
}
5. This code will will only print the mirror of the tree
void tree_mirror(struct node* node)
{
struct node *temp;
if (node==NULL)
{
return;
}
else
{
tree_mirror(node->left);
tree_mirror(node->right);
// Swap the pointers in this node
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
Write a C program to compute the maximum depth in a tree?
Discuss it!
int maxDepth(struct node* node)
{
if (node==NULL)
{
return(0);
}
else
{
int leftDepth = maxDepth(node->left);
int rightDepth = maxDepth(node->right);
if (leftDepth > rightDepth) return(leftDepth+1);
else return(rightDepth+1);
}
}
6. Write C code to return a pointer to the nth node of an inorder traversal of a BST.
Discuss it!
typedef struct node
{
int value;
struct node *left;
struct node *right;
}mynode;
mynode *root;
static ctr;
void nthnode(mynode *root, int n, mynode **nthnode /* POINTER TO A
POINTER! */);
int main()
{
mynode *temp;
root = NULL;
// Construct the tree
add(19);
add(20);
...
add(11);
// Plain Old Inorder traversal
// Just to see if the next function is really returning the nth node?
inorder(root);
// Get the pointer to the nth Inorder node
nthinorder(root, 6, &temp);
printf("n[%d]n, temp->value);
return(0);
}
// Get the pointer to the nth inorder node in "nthnode"
void nthinorder(mynode *root, int n, mynode **nthnode)
{
static whichnode;
static found;
if(!found)
{
if(root)
{
7. nthinorder(root->left, n , nthnode);
if(++whichnode == n)
{
printf("nFound %dth noden", n);
found = 1;
*nthnode = root; // Store the pointer to the nth node.
}
nthinorder(root->right, n , nthnode);
}
}
}
inorder(mynode *root)
{
// Plain old inorder traversal
}
// Function to add a new value to a Binary Search Tree
add(int value)
{
mynode *temp, *prev, *cur;
temp = malloc(sizeof(mynode));
temp->value = value;
temp->left = NULL;
temp->right = NULL;
if(root == NULL)
{
root = temp;
}
else
{
prev = NULL;
cur = root;
while(cur)
{
prev = cur;
cur = (value < cur->value)? cur->left : cur->right;
}
if(value > prev->value)
prev->right = temp;
else
prev->left = temp;
}
8. }
There seems to be an easier way to do this, or so they say. Suppose
each node also
has a weight associated with it. This weight is the number of nodes
below it and
including itself. So, the root will have the highest weight (weight of
its left subtree
+ weight of its right subtree + 1). Using this data, we can easily find
the nth inorder
node.
Note that for any node, the (weight of the leftsubtree of a node + 1)
is its inorder
rankin the tree!. Thats simply because of how the inorder traversal
works (left->root->right).
So calculate the rank of each node and you can get to the nth inorder
node easily.
But frankly speaking, I really dont know how this method is any simpler
than the
one I have presented above. I see more work to be done here (calculate
thw weights,
then calculate the ranks and then get to the nth node!).
Also, if (n > weight(root)), we can error out saying that this tree
does not have
the nth node you are looking for.
9. Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their
time complexities?
Discuss it!
Preorder
preorder(mynode *root)
{
if(root)
{
printf("Value : [%d]", root->value);
preorder(root->left);
preorder(root->right);
}
}
Postorder
postorder(mynode *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
printf("Value : [%d]", root->value);
}
}
Inorder
inorder(mynode *root)
{
if(root)
{
inorder(root->left);
printf("Value : [%d]", root->value);
inorder(root->right);
}
}
Time complexity of traversals is O(n).
10. Write a C program to create a copy of a tree
Discuss it!
mynode *copy(mynode *root)
{
mynode *temp;
if(root==NULL)return(NULL);
temp = (mynode *) malloc(sizeof(mynode));
temp->value = root->value;
temp->left = copy(root->left);
temp->right = copy(root->right);
return(temp);
}
Write C code to check if a given binary tree is a binary search tree or not?
Discuss it!
int isThisABST(struct node* mynode)
{
if (mynode==NULL) return(true);
if (node->left!=NULL && maxValue(mynode->left) > mynode->data)
return(false);
if (node->right!=NULL && minValue(mynode->right) <= mynode->data)
return(false);
if (!isThisABST(node->left) || !isThisABST(node->right))
return(false);
return(true);
}
11. Write C code to implement level order traversal of a tree.
Discuss it!
If this is the tree,
1
2 3
5 6 7 8
its level order traversal would be
1 2 3 5 6 7 8
You need to use a queue to do this kind of a traversal
Let t be the tree root.
while (t != null)
{
visit t and put its children on a FIFO queue;
remove a node from the FIFO queue and
call it t;
// Remove returns null when queue is empty
}
Pseduocode
Level_order_traversal(p)
{
while(p)
{
Visit(p);
If(p->left)Q.Add(p->left);
If(p->right)Q.Add(p->right);
Delete(p);
}
}
12. Here is some C code (working :))..
#include <stdio.h>
typedef struct node
{
int value;
struct node *right;
struct node *left;
}mynode;
mynode *root;
add_node(int value);
void levelOrderTraversal(mynode *root);
int main(int argc, char* argv[])
{
root = NULL;
add_node(5);
add_node(1);
add_node(-20);
add_node(100);
add_node(23);
add_node(67);
add_node(13);
printf("nnnLEVEL ORDER TRAVERSALnn");
levelOrderTraversal(root);
getch();
}
// Function to add a new node...
add_node(int value)
{
mynode *prev, *cur, *temp;
temp = (mynode *) malloc(sizeof(mynode));
temp->value = value;
14. }
}
Write a C program to delete a node from a Binary Search Tree?
Discuss it!
The node to be deleted might be in the following states
The node does not exist in the tree - In this case you have nothing
to delete.
The node to be deleted has no children - The memory occupied by this
node must be
freed and either the left link or the right link of the parent of
this node must
be set to NULL.
The node to be deleted has exactly one child - We have to adjust the
pointer of the
parent of the node to be deleted such that after deletion it points
to the child
of the node being deleted.
The node to be deleted has two children - We need to find the inorder
successor of
the node to be deleted. The data of the inorder successor must be
copied into the
node to be deleted and a pointer should be setup to the inorder
successor. This inorder
successor would have one or zero children. This node should be
deleted using the
same procedure as for deleting a one child or a zero child node. Thus
the whole logic
of deleting a node with two children is to locate the inorder
successor, copy its
data and reduce the problem to a simple deletion of a node with one
or zero children.
Here is some C code for these two situations
Situation 1
16. cur = (item < cur->next)? cur->left:cur->right;
}
if(cur == NULL)
{
printf("nItem to be deleted not found!n");
return(head);
}
// Item found, now delete it
if(cur->left == NULL)
q = cur->right;
else if(cur->right == NULL)
q = cur->left;
else
{
// Obtain the inorder successor and its parent
psuc = cur;
cur = cur->left;
while(suc->left!=NULL)
{
psuc = suc;
suc = suc->left;
}
if(cur==psuc)
{
// Situation 1
suc->left = cur->right;
}
else
{
// Situation 2
suc->left = cur->left;
psuc->left = suc->right;
suc->right = cur->right;
}
q = suc;
}
17. // Attach q to the parent node
if(parent->left == cur)
parent->left=q;
else
parent->rlink=q;
freeNode(cur);
return(head);
}
Write C code to search for a value in a binary search tree (BST).
Discuss it!
mynode *search(int value, mynode *root)
{
while(root!=NULL && value!=root->value)
{
root = (value < root->value)?root->left:root->right;
}
return(root);
}
Here is another way to do the same
mynode *recursive_search(int item, mynode *root)
{
if(root==NULL || item == root->value){return(root);}
if(item<root->info)return{recursive_search(item, root->left);}
return{recursive_search(item, root->right);}
18. Write C code to count the number of leaves in a tree
Discuss it!
void count_leaf(mynode *root)
{
if(root!=NULL)
{
count_leaf(root->left);
if(root->left == NULL && root->right==NULL)
{
// This is a leaf!
count++;
}
count_leaf(root->right);
}
Write C code for iterative preorder, inorder and postorder tree traversals
Discuss it!
Here is a complete C program which prints a BST using both recursion
and iteration.
The best way to understand these algorithms is to get a pen and a paper
and trace
out the traversals (with the stack or the queue) alongside. Dont even
try to memorize
these algorithms!
#include <stdio.h>
typedef struct node
{
int value;
struct node *right;
struct node *left;
}mynode;
mynode *root;
add_node(int value);
void postorder(mynode *root);
void inorder(mynode *root);
23. printf("[%d] ", root->value);
root = save[--top];
}
printf("[%d] ", root->value);
root = (top != 0) ? save[--top] : (mynode *) NULL;
}
}
And here is the output...
Creating the root..
Preorder (R) : [5] [1] [-20] [100] [23] [13] [67]
Preorder (I) : [5] [1] [-20] [100] [23] [13] [67]
Postorder (R) : [-20] [1] [13] [67] [23] [100] [5]
Postorder (R) : [-20] [1] [13] [67] [23] [100] [5]
Inorder (R) : [-20] [1] [5] [13] [23] [67] [100]
Inorder (I) : [-20] [1] [5] [13] [23] [67] [100]
Construct a tree given its inorder and preorder traversal strings. Similarly construct a tree
given its inorder and post order traversal strings.
Discuss it!
For Inorder And Preorder traversals
inorder = g d h b e i a f j c
preorder = a b d g h e i c f j
Scan the preorder left to right using the inorder sequence to separate
left and right
subtrees. For example, "a" is the root of the tree; "gdhbei" are in the
left subtree;
"fjc" are in the right subtree. "b" is the next root; "gdh" are in the
left subtree;
"ei" are in the right subtree. "d" is the next root; "g" is in the left
subtree;
"h" is in the right subtree.
24. For Inorder and Postorder traversals
Scan postorder from right to left using inorder to separate left and
right subtrees.
inorder = g d h b e i a f j c
postorder = g h d i e b j f c a
Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right
subtree.
For Inorder and Levelorder traversals
Scan level order from left to right using inorder to separate left and
right subtrees.
inorder = g d h b e i a f j c
level order = a b c d e f g h i j
Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right
subtree.
Here is some working code which creates a tree out of the Inorder and
Postorder
traversals. Note that here the tree has been represented as an array.
This really
simplifies the whole implementation.
Converting a tree to an array is very easy
Suppose we have a tree like this
A
B C
25. D E F G
The array representation would be
a[1] a[2] a[3] a[4] a[5] a[6] a[7]
A B C D E F G
That is, for every node at position j in the array, its left child will
be stored
at position (2*j) and right child at (2*j + 1). The root starts at
position 1.
// CONSTRUCTING A TREE GIVEN THE INORDER AND PREORDER SEQUENCE
#include<stdio.h>
#include<string.h>
#include<ctype.h>
/*-------------------------------------------------------------
* Algorithm
*
* Inorder And Preorder
* inorder = g d h b e i a f j c
* preorder = a b d g h e i c f j
* Scan the preorder left to right using the inorder to separate left
* and right subtrees. a is the root of the tree; gdhbei are in the
* left subtree; fjc are in the right subtree.
*------------------------------------------------------------*/
static char io[]="gdhbeiafjc";
static char po[]="abdgheicfj";
static char t[100][100]={'0'}; //This is where the final tree will be
stored
static int hpos=0;
void copy_str(char dest[], char src[], int pos, int start, int end);
void print_t();
int main(int argc, char* argv[])
{
int i,j,k;
char *pos;
int posn;
26. // Start the tree with the root and its
// left and right elements to start off
for(i=0;i<strlen(io);i++)
{
if(io[i]==po[0])
{
copy_str(t[1],io,1,i,i); // We have the root here
copy_str(t[2],io,2,0,i-1); // Its left subtree
copy_str(t[3],io,3,i+1,strlen(io)); // Its right subtree
print_t();
}
}
// Now construct the remaining tree
for(i=1;i<strlen(po);i++)
{
for(j=1;j<=hpos;j++)
{
if((pos=strchr((const char *)t[j],po[i]))!=(char *)0 &&
strlen(t[j])!=1)
{
for(k=0;k<strlen(t[j]);k++)
{
if(t[j][k]==po[i]){posn=k;break;}
}
printf("nSplitting [%s] for po[%d]=[%c] at %d..n",
t[j],i,po[i],posn);
copy_str(t[2*j],t[j],2*j,0,posn-1);
copy_str(t[2*j+1],t[j],2*j+1,posn+1,strlen(t[j]));
copy_str(t[j],t[j],j,posn,posn);
print_t();
}
}
}
}
// This function is used to split a string into three seperate strings
// This is used to create a root, its left subtree and its right
subtree
void copy_str(char dest[], char src[], int pos, int start, int end)
{
char mysrc[100];
strcpy(mysrc,src);
dest[0]='0';
strncat(dest,mysrc+start,end-start+1);
27. if(pos>hpos)hpos=pos;
}
void print_t()
{
int i;
for(i=1;i<=hpos;i++)
{
printf("nt[%d] = [%s]", i, t[i]);
}
printf("n");
}
Find the closest ancestor of two nodes in a tree.
Discuss it!
Here is some working C code...
#include <stdio.h>
typedef struct node
{
int value;
struct node *right;
struct node *left;
}mynode;
mynode *root;
mynode *add_node(int value);
void levelOrderTraversal(mynode *root);
mynode *closestAncestor(mynode* root, mynode* p, mynode* q);
int main(int argc, char* argv[])
{
mynode *node_pointers[7], *temp;
root = NULL;
// Create the BST.
// Store the node pointers to use later...
node_pointers[0] = add_node(5);
node_pointers[1] = add_node(1);
node_pointers[2] = add_node(-20);
28. node_pointers[3] = add_node(100);
node_pointers[4] = add_node(23);
node_pointers[5] = add_node(67);
node_pointers[6] = add_node(13);
printf("nnnLEVEL ORDER TRAVERSALnn");
levelOrderTraversal(root);
// Calculate the closest ancestors of a few nodes..
temp = closestAncestor(root, node_pointers[5], node_pointers[6]);
printf("nnClosest ancestor of [%d] and [%d] is [%d]nn",
node_pointers[5]->value,
node_pointers[6]->value,
temp->value);
temp = closestAncestor(root, node_pointers[2], node_pointers[6]);
printf("nnClosest ancestor of [%d] and [%d] is [%d]nn",
node_pointers[2]->value,
node_pointers[6]->value,
temp->value);
temp = closestAncestor(root, node_pointers[4], node_pointers[5]);
printf("nnClosest ancestor of [%d] and [%d] is [%d]nn",
node_pointers[4]->value,
node_pointers[5]->value,
temp->value);
temp = closestAncestor(root, node_pointers[1], node_pointers[3]);
printf("nnClosest ancestor of [%d] and [%d] is [%d]nn",
node_pointers[1]->value,
node_pointers[3]->value,
temp->value);
temp = closestAncestor(root, node_pointers[2], node_pointers[6]);
printf("nnClosest ancestor of [%d] and [%d] is [%d]nn",
node_pointers[2]->value,
node_pointers[6]->value,
temp->value);
}
29. // Function to add a new node to the tree..
mynode *add_node(int value)
{
mynode *prev, *cur, *temp;
temp = (mynode *) malloc(sizeof(mynode));
temp->value = value;
temp->right = NULL;
temp->left = NULL;
if(root==NULL)
{
printf("nCreating the root..n");
root = temp;
return;
}
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
cur=(value<cur->value)?cur->left:cur->right;
}
if(value < prev->value)
prev->left=temp;
else
prev->right=temp;
return(temp);
}
// Level order traversal..
void levelOrderTraversal(mynode *root)
{
mynode *queue[100] = {(mynode *)0};
int size = 0;
int queue_pointer = 0;
while(root)
{
printf("[%d] ", root->value);
if(root->left)
31. Here is the tree for you to visualize...
5 (node=0)
1 (node=1) 100 (node=3)
-20 (node=2) 23 (node=4)
13 (node=5) 67 (node=6)
Here is the output...
LEVEL ORDER TRAVERSAL
[5] [1] [100] [-20] [23] [13] [67]
Closest ancestor of [67] and [13] is [23]
Closest ancestor of [-20] and [13] is [5]
Closest ancestor of [23] and [67] is [100]
Closest ancestor of [1] and [100] is [5]
Closest ancestor of [-20] and [13] is [5]
32. Given an expression tree, evaluate the expression and obtain a paranthesized form of the
expression.
Discuss it!
The code below prints the paranthesized form of a tree.
infix_exp(p)
{
if(p)
{
printf("(");
infix_exp(p->left);
printf(p->data);
infix_exp(p->right);
printf(")");
}
}
How do you convert a tree into an array?
Discuss it!
The conversion is based on these rules
If i > 1, i/2 is the parent
If 2*i > n, then there is no left child, else 2*i is the left child.
If (2*i + 1) > n, then there is no right child, else (2*i + 1) is the
right child.
Converting a tree to an array is very easy
Suppose we have a tree like this
A
B C
D E F G
The array representation would be
a[1] a[2] a[3] a[4] a[5] a[6] a[7]
33. A B C D E F G
That is, for every node at position i in the array, its left child will
be stored
at position (2*i) and right child at (2*i + 1). The root starts at
position 1.
Write pseudocode to add a new node to a Binary Search Tree (BST)
Discuss it!
Here is a C code to construct a BST right from scratch...
#include <stdio.h>
typedef struct node
{
int value;
struct node *right;
struct node *left;
}mynode;
mynode *root;
add_node(int value);
void postorder(mynode *root);
void inorder(mynode *root);
void preorder(mynode *root);
int main(int argc, char* argv[])
{
root = NULL;
add_node(5);
add_node(1);
add_node(-20);
add_node(100);
add_node(23);
add_node(67);
add_node(13);
printf("nPreorder : ");
preorder(root);
printf("nnPostorder : ");
postorder(root);