To find height of a binary search tree - height

/*
* To find the Height of a BST tree
*/
public void findHeight(){
if(this.root == null){
System.out.println("BST Tree is Empty ");
}
else
findHeight(this.root);
}
public int findHeight(Tnode temp){
if(temp == null){
System.out.println("BST Tree is Empty ");
return -1;
}
else{
return 1 + Math.max(findHeight(temp.getLeft()) ,findHeight(temp.getRight()) ) ;
}
}
Program is running infinitely.Not able to find the reason , It would be helpfull ,if some one guides me
Thanks in advance

Are you sure the findHeight() function doesn't return anything? Are you expecting anything from that function? Posting more code would help.

"BST Tree is Empty" will also be printed at every terminal leaf of the tree.
To find out what's going on, you could add some debugging output:
private spaces(int len){
String s = " ";
while (s.Length < len) {
s += " ";
}
return s.substring(0, len);
}
public int findHeight(Tnode temp, int nesting, String msg){
String margin = spaces(2*nesting);
if(temp == null){
System.out.println(margin + msg + ": no sub-tree to explore");
return -1;
}
else{
System.out.println(margin + msg);
int hl = findHeight(temp.getLeft(), nesting + 1, "left");
int hr = findHeight(temp.getRight(), nesting + 1, "right");
return 1 + (hl >= hr ? hl : hr) ;
}
}
Your endless recursion might be due to some error in your tree structure. If your left/right child references are never null, the recursion won't terminate.

Related

How to recursivly find the height of a Trie Tree

I'm having a little trouble figuring out how to find the height of a trie tree data structure. I know for an AVL tree a simple recursive height function would be:
height(nodeType *node) const
{
if(node == NULL)
return 0;
// if tree is not empty height is 1 + max of either path
return 1 + std::max(height(node->left), height(node->right));
}
but now my trie tree has a children with 26 different indexes, there must be a simple way to find the maximum height without typing out all 26 different possible indexes. How could I go about this?
int height(trieNodeType *node) const
{
if(node == NULL)
return 0;
for(int i = 0; i < 26; i ++) {
//has to be something to do with a for loop,
//i know that much
}
}
Looping is the way to go.
C++11:
if (node == nullptr) return 0;
auto i = std::begin(node->children);
auto end = std::end(node->children);
auto max_height = height(i++);
while (i != end) {
max_height = std::max(max_height, height(i++));
}
return 1 + max_height;
C++ <11.
if (node == NULL) return 0;
trieNodeType ** i = node->children;
trieNodeType ** end = i + (sizeof(node->children) / sizeof(trieNodeType *));
int max_height = height(i++);
while (i != end) {
max_height = std::max(max_height, height(i++));
}
return 1 + max_height;
Another C++11 approach
return 1 + std::accumulate(std::begin(node->children) + 1, std::end(node->children),
height(node->children[0]),
[](int curMax, trieNodeType* child) { return std::max(curMax, height(child)); });
There exists also std::max_element function, but in straightforward implementation using it would lead to calculating the height of the same child node several times.

List and count the most weight path from the root to the leafs of a binary tree

I have to return the number of nodes and the weight of the most weight path from the root to some leaf. Note that the tree is not a Binary Search Tree, is unsorted.
i.e.:
6
/ \
9 6
/ / \
3 1 19
Then, I have to return the integer 6 + 6 + 19 = 31 and print the node 6 - 6 - 19
So, this is my code:
int heavierPath ( Node * tree ) {
if ( ! tree ) return 0;
int leftWeight = heavierPath( tree->left );
int rightWeight= heavierPath( tree->right );
if ( leftWeight >= rightWeight ) {
if ( tree->left )
cout << tree->left->value << endl;
return tree->value + leftWeight;
}
else {
cout << tree->right->value << endl;
return tree->value + rightWeight;
}
};
And the result is 31, but I see all the nodes values in the terminal.
How can I do to fix it and print only the elements that lies in the heavier path? (only recursive)
Thanks!
This appears to work after I edited it.
Take a look at: http://ideone.com/OGcyun as an example.
Your problem:
Consider the graph as:
6
/ \
9 6
/ / \
3 1 19
Number each node so:
0
/ \
1 2
/ / \
3 4 5
Consider the case where you are at node 1.
You ask for the better path which gives you leftWeight = 3 and rightweight = 0 and you print the "better" path, 3. which isn't part of the end result.
The solution
To solve this problem, I passed up additional data up in a retstruct which contain the path (the heaviest path up to this point), value (to make printing easier), sum (to determine the better path).
Then I changed the function to:
retstruct* heavierPath ( Node * tree ) {
if ( ! tree ) return new retstruct();
//Get both paths
retstruct* leftWeight = heavierPath( tree->left );
retstruct* rightWeight= heavierPath( tree->right );
//Find the "heavier" path
if ( leftWeight->sum >= rightWeight->sum ) {
//Delete lighter path
delete_retstruct(rightWeight);
//Pass up the better path with the correct data
return new retstruct(leftWeight, tree->value, tree->value + leftWeight->sum);
} else {
//Delete lighter path
delete_retstruct(leftWeight);
//Pass up the better path with the correct data
return new retstruct(rightWeight, tree->value, tree->value + rightWeight->sum);
}
};
Added the delete_retstruct function:
void delete_retstruct (retstruct* path) {
if (path->path == NULL) {
delete path;
} else {
delete_retstruct(path->path);
}
}
and the printPath function:
void printPath (retstruct* path) {
if (path->path != NULL) {
std::cout << " - " << path->value;
printPath(path->path);
}
}
This is used like so:
retstruct* path = heavierPath(tree);
//Print sum
std::cout << "Sum: " << path->sum << std::endl;
//Print path
std::cout << "Path: " << path->value;
printPath(path->path);
std::cout << std::endl;
Output:
Sum: 31
Path: 6 - 6 - 19
My suggestion is to make two functions,first function will find the leaf where path from root to it is maximum. So assuming you have pointer to such leaf here is the function to print the path.
bool print(struct node *r, struct node *leaf)
{
if (r == NULL)
return false;
//will print if it is leaf or on path to leaf
if (r == leaf || print(r->left, leaf) || print(r->right, leaf) )
{
printf("%d ", r->val); // this will print in reverse order
// if you want to print from root, store values in stack and then print the value after the function call
return true;
}
return false;
}
The problem is that you are mixing printing the node with finding the sum. The later has to visit all child-nodes while printing only has to visit the ones in the path.
Below is a possible solution:
#include <iostream>
#include <unordered_map>
struct Node
{
Node(int value = 0, Node* left = nullptr, Node* right = nullptr) :
value{value},
left{left},
right{right}
{}
int value;
Node* left;
Node* right;
};
std::unordered_map<Node*, int> map;
int pathSum(Node* node)
{
if (node == nullptr)
{
return 0;
}
else if (map.find(node) == map.end())
{
return (pathSum(node->left) > pathSum(node->right))
? (map[node] = node->value + pathSum(node->left))
: (map[node] = node->value + pathSum(node->right));
}
else
{
return map[node];
}
}
void printPath(Node* node)
{
if (node == nullptr)
{
return;
}
std::cout << node->value << std::endl;
if (pathSum(node->left) > pathSum(node->right))
{
printPath(node->left);
}
else
{
printPath(node->right);
}
}
int main() {
Node* tree = new Node(6,
new Node(9,
new Node(3)),
new Node(6,
new Node(1),
new Node(19)));
std::cout << "Biggest Sum: " << pathSum(tree) << std::endl;
std::cout << "Biggest Sum Path: " << std::endl;
printPath(tree);
return 0;
}
In recursive solutions such as this, it's a good idea to cache the results hence the std::unordered_map. The code has been tested at Ideone.

Implementation of BFS

I have implemented Breadth First Search. The adjacency matrix(adj[][]) represents the relationship among different nodes and the nodes are stored in nodes[].
However, I do not get the required traversal. Please help me out. Below is my code. There are no syntax errors. It is probably a logical error that I am not able to find out by debugging.
insert(nodes[0]);
nos = nos + 1;
visited[nos] = nodes[0];
while(front != -1)
{
char ch = remove();
for(int i=0;i<n;i++)
{
if(ch == nodes[i])
{
pos = i;
}
}
for(int j=0;j<n;j++)
{
if(adj[j][pos] == 1)
{
for(int k=0;k<=nos;k++)
{
if(visited[k] == nodes[j])
{
goto end;
}
}
nos = nos + 1;
visited[nos] = nodes[j];
insert(nodes[j]);
end:continue;
}
}
}
Try this.. it seems to be working for me
def bfs(graph, start, goal):
if start == goal:
return None
frontier = [start]
explored = []
num_explored = 0
while len(frontier) > 0:
node = frontier.pop(0)
explored.append(node)
for edge in networkx.edges(graph, node):
child = State(graph, node)
if (child not in explored) and (child not in frontier):
if child == goal:
print "Path found in BFS"
return child
else:
frontier.append(child)
num_explored = num_explored + 1
print "BFS path failed"
return None

How to print the nodes in bst whose grandparent is a multiple of five?

I'm sorry that was my first time for asking question in stackoverflow. I just read the faq and knew I disobeyed the rules. I was not just coping and pasting the questions. I use an in-order traverse method to do the recursion and check whether the node is a multiple of five and I don't know what to do next. Should I use a flag to check something?
void findNodes(BSTNode<Key,E> *root) const
{
if(root==NULL) return;
else
{
if(root->key()%5==0)//I know it's wrong, but I don't know what to do
{
findNodes(root->left());
cout<<root->key()<<" ";
findNodes(root->right());
}
else
{
findNodes(root->left());
findNodes(root->right());
}
}
}
Printing nodes whose grandparent is a multiple of 5 is complicated as you have to look "up" the tree. It is easier if you look at the problem as find all the nodes who are a multiple of 5 and print their grandchildren, as you only have to go down the tree.
void printGrandChildren(BSTNode<Key,E> *root,int level) const{
if(!root) return;
if(level == 2){
cout<<root->key()<<" ";
return;
}else{
printGrandChildren(root->left(),level+1);
printGrandChildren(root->right(),level+1);
}
}
Then modify your findNodes to
void findNodes(BSTNode<Key,E> *root) const
{
if(root==NULL) return;
else
{
if(root->key()%5==0)
{
printGrandChildren(root,0);
}
else
{
findNodes(root->left());
findNodes(root->right());
}
}
}
Try this:
int arr[height_of_the_tree]; //arr[10000000] if needed;
void findNodes(BSTNode<Key,E> *root,int level) const {
if(root==NULL) return;
arr[level] = root -> key();
findNodes(root -> left(), level + 1);
if(2 <= level && arr[level - 2] % 5 == 0) cout << root->key() << " ";
findNodes(root -> right(), level + 1);
}
int main() {
...
findNodes(Binary_search_tree -> root,0);
...
}
Replace the following
cout<<root->key()<<" ";
with
if(root->left)
{
if(root->left->left)
cout<<root->left->left->key()<< " ";
if(root->left->right)
cout<<root->left->right->key()<< " ";
}
if(root->right)
{
if(root->right->left)
cout<<root->right->left->key()<< " ";
if(root->right->right)
cout<<root->right->right->key()<< " ";
}
If you're just trying to print our all child nodes which have an ancestor which has a key which is a multiple of 5, then one way would be to pass a bool to your findNodes function which stores this fact.
Something along the lines of:
void findNodes(BSTNode<Key,E>* node, bool ancesterIsMultOf5) const
{
if (node)
{
if (ancesterIsMultOf5)
std::cout << node->key() << std::endl;
ancesterIsMultOf5 |= (node->key() % 5 == 0);
findNodes(node->left(), ancesterIsMultOf5);
findNodes(node->right(), ancesterIsMultOf5);
}
}
Alternately, if you're trying to draw the tree, it has been answered before: C How to "draw" a Binary Tree to the console

Nightmare Expression Tree with over-constrained class

I inadvertently let my students overconstrain a shared class used to solve the following problem. I realized it might be a problem denizens of this site might enjoy.
The first team/function, getNodes, takes a string representing a prefix expression using signed integers and the four operations +, -, *, and / and produces the corresponding null terminated linked list of tokens, using the class Node, with tokens linked through the "right" pointer.
The second team/function, getTree, takes a similar string, passes it to getNodes, and relinks the resultant nodes to be an expression tree.
The third team/function, evaluate, takes a similar string, passes it to getTree, and evaluates the resultant expression tree to form an answer.
The over-constrained exptree.h follows. The problem has to be solved by writing just the three functions defined above, no additional functions.
#ifndef EXPTREE_H_
#define EXPTREE_H_
using namespace std;
enum Ops{ADD, SUB, MUL, DIV, NUM};
class Node {
private:
int num;
Ops op;
Node *left, *right;
public:
friend Node *getNodes(string d);
friend Node *getTree(string d);
friend int evaluate (string);
};
int evaluate(string d);
Node *getNodes(string d);
Node *getTree(string d);
#endif
The only libraries that can be used are these
#include <iostream>
#include <vector>
#include <string>
#include "exptree.h"
For those of you worried about my students, I will be pointing out today how just a couple of more well placed functions would allow this problem to be easily solved. I know the expression tree can code rational numbers and not just integers. I'll be pointing that out today as well.
Here is the driver program I gave them based on their specs.
#include <iostream>
#include <string>
#include "exptree.h"
using namespace std;
void test(string s, int target) {
int result = evaluate(s);
if (result == target)
cout << s << " correctly evaluates to " << target << endl;
else
cout << s << "(" << result
<< ") incorrectly evaluates to " << target << endl;
}
int main() {
test("42", 42);
test("* - / 4 2 1 42", 42);
test("* - / -4 +2 -1 2", -2);
test("* - / -4 +2 -1 2 ", -2);
test("* 9 6", 54);
return 0;
}
Can you write the three functions in as elegant a fashion as possible to solve this nightmarish problem?
The getNodes and getTree functions would be pretty trivial to write under these constraints, so I just skipped ahead to the interesting part. You would naturally evaluate an expression tree recursively, but that is not an option here because the eval function only takes a string. Sure, you could restringify the remaining tree into a prefix expression and call eval recursively on that, but that would just be stupid.
First, I convert the expression tree into a postfix expression, using an explicit stack as the poor man's recursion. Then I evaluate that with the standard operand stack.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "exptree.h"
int evaluate(string d){
Node* tree = getTree(d);
//convert tree to postfix for simpler evaluation
vector<Node*> node_stack;
node_stack.push_back(tree);
Node postfix_head;
Node* postfix_tail = &postfix_head;
while(node_stack.size() > 0){
Node* place = node_stack.back();
if(place->left == 0){
if(place->right == 0){
postfix_tail->right = place;
node_stack.pop_back();
} else {
node_stack.push_back(place->right);
place->right = 0;
}
} else {
node_stack.push_back(place->left);
place->left = 0;
}
}
//evaluate postfix
Node* place = postfix_head.right;
vector<int> stack;
while(place != 0){
if(place->op != NUM){
int operand_a, operand_b;
operand_b = stack.back();
stack.pop_back();
operand_a = stack.back();
stack.pop_back();
switch(place->op){
case ADD:
stack.push_back(operand_a + operand_b);
break;
case SUB:
stack.push_back(operand_a - operand_b);
break;
case MUL:
stack.push_back(operand_a * operand_b);
break;
case DIV:
stack.push_back(operand_a / operand_b);
break;
}
} else {
stack.push_back(place->num);
}
place = place->right;
}
return stack.back();
}
I think that "no additional functions" is a too tough requirement. The easiest way to implement e.g. getTree is probably recursive, and it requires defining an additional function.
Node* relink(Node* start) // builds a tree; returns the following node
{
if (start->op == NUM)
{
Node* result = start->right;
start->left = start->right = NULL;
return result;
}
else
{
start->left = start->right;
start->right = relink(start->left);
return relink(start->right);
}
}
Node* getTree(string d)
{
Node* head = getNodes(d);
relink(head);
return head;
}
I could implement recursion by using an explicit stack (implemented by std::vector) but that is ugly and obscure (unless you want you students to practice exactly that).
For what its worth, here is the solution I coded up just before I posted the question
#include <iostream>
#include <vector>
#include "exptree.h"
using namespace std;
Node *getNodes(string s) {
const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;
Node *list;
int sign, num;
s += " "; // this simplifies a lot of logic, allows trailing white space to always close off an integer
list = (Node *) (num = sign = 0);
for (int i=0; i<s.size(); ++i) {
char c = s[i]; // more efficient and cleaner reference to the current character under scrutiny
if (isdigit(c)) {
if (sign == 0) sign = 1; // if sign not set, then set it. A blank with a sign==0 now signifies a blank that can be skipped
num = 10*num + c - '0';
} else if (((c=='+') || (c=='-')) && isdigit(s[i+1])) { // another advantage of adding blank to string above so don't need a special case
sign = (c=='+') ? 1 : -1;
} else if ( !isspace(c) && (c != '+') && (c != '-') && (c != '*') && (c != '/')) {
cout << "unexpected character " << c << endl;
exit(1);
} else if (!isspace(c) || (sign != 0)) { // have enough info to create next Node
list->left = (list == 0) ? (list = new Node) : (list->left->right = new Node); // make sure left pointer of first Node points to last Node
list->left->right = 0; // make sure list is still null terminated
list->left->op = (c=='+' ? ADD : (c=='-' ? SUB : (c=='*' ? MUL : (c=='/' ? DIV : NUM)))); // choose right enumerated type
list->left->num = (list->left->op==NUM) ? sign*num : MININT; // if interior node mark number for evaluate function
num = sign = 0; // prepare for next Node
}
}
return list;
}
Node *getTree(string s) {
Node *nodes = getNodes(s), *tree=0, *root, *node;
vector<Node *> stack;
if (nodes == 0) return tree;
root = tree = nodes;
nodes = nodes->right;
for (node=nodes; node != 0; node=nodes) {
nodes = nodes->right;
if (root->op != NUM) { // push interior operator Node on stack til time to point to its right tree
stack.push_back(root);
root = (root->left = node); // set interior operator Node's left tree and prepare to process that left tree
} else {
root->left = root->right = 0; // got a leaf number Node so finish it off
if (stack.size() == 0) break;
root = stack.back(); // now pop operator Node off the stack
stack.pop_back();
root = (root->right = node); // set its left tree and prepare to process that left tree
}
}
if ((stack.size() != 0) || (nodes != 0)) {
cout << "prefix expression has missing or extra terms" << endl;
exit(1);
}
return tree;
}
int evaluate(string s) {
// MININT is reserved value signifying operator waiting for a left side value, low inpact since at edge of representable integers
const int MAXINT =(int)(((unsigned int)-1) >> 1), MININT = -MAXINT -1;
Node *tree = getTree(s);
vector<Node *> stack;
int v = 0; // this is value of a leaf node (a number) or the result of evaluating an interior node
if (tree == 0) return v;
do {
v = tree->num;
if (tree->op != NUM) {
stack.push_back(tree);
tree = tree->left; // prepare to process the left subtree
} else while (stack.size() != 0) { // this while loop zooms us up the right side as far as we can go (till we come up left side or are done)
delete tree; // done with leaf node or an interior node we just finished evaluating
tree = stack.back(); // get last interior node from stack
if (tree->num == MININT) { // means returning up left side of node, so save result for later
tree->num = v;
tree = tree->right; // prepare to evaluate the right subtree
break; // leave the "else while" for the outer "do while" which handles evaluating an expression tree
} else { // coming up right side of an interior node (time to calculate)
stack.pop_back(); // all done with interior node
v = tree->op==ADD ? tree->num+v : (tree->op==SUB ? tree->num-v : (tree->op==MUL ? tree->num*v : tree->num/v)) ;
}
}
} while (stack.size() != 0);
return v;
}