473,951 Members | 29,657 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

finding height of a binary search tree without using recursion

14 New Member
I have been given this interface,
Expand|Select|Wrap|Line Numbers
  1. interface BinarySearchTree {
  2.    public void insert(Integer data);
  3.    public int size();
  4.    public int height();
  5.    public boolean contains(Integer target);
  6. }
  7.  
and I have to implement BST with all these functions. I have implemented the first insert and size like this way -
Expand|Select|Wrap|Line Numbers
  1. class Node {
  2.     Node left, right;
  3.     Integer data;
  4.     Node () {
  5.         left = right = null;
  6.         data = 0;
  7.     }
  8. }
  9.  
  10. public class BSTree extends Node implements BinarySearchTree {
  11.     static Node root;
  12.     static int countNode;
  13.     /**
  14.      * Creates a new instance of BSTree
  15.      */
  16.     public BSTree() {
  17.         root = null;
  18.     }
  19.     public void insert(Integer data) {
  20.         if (root == null) {
  21.             root.data = data;
  22.             countNode++;
  23.         } else {
  24.             Node temp = new Node();
  25.             temp = root;
  26.             while (temp != null) {
  27.                 if (temp.data < data) temp = temp.right;
  28.                 else {
  29.                     temp = temp.left;
  30.                 }
  31.                 temp.data = data;
  32.                 countNode++;
  33.             }
  34.         }
  35.     }
  36.     public int size () {
  37.         return countNode;
  38.     }
  39.  
  40.     public int height() { 
  41.         Node temp = new Node();
  42.         /* could have used these for recursion 
  43.         final boolean flag = true;
  44.         if (flag) */
  45.             temp = root;
  46.         if (temp == null) {
  47.             return 0;
  48.         } else {
  49.         /* would have been easy to find height using this recursion
  50.             return 1 + max(height(temp.left), height(temp.right)); */
  51.         }
  52.     }
  53.  
  54.     public boolean contains (Integer target) {
  55.  
  56.     }
  57.     /**
  58.      * @param args the command line arguments
  59.      */
  60.     public static void main(String[] args) {
  61.  
  62.         BSTree bs = new BSTree();
  63.         bs.insert(12);
  64.         bs.insert(3);
  65.         bs.insert(14);
  66.     }
  67.  
  68. }
  69.  
  70.  
The objective requires that the height be implemented without using an argument. Do you have some ideas?
Jan 6 '08
17 16421
JosAH
11,448 Recognized Expert MVP
I must have been thinking of Ents
How silly: Ents are totally extinct because they were all male. You can use
final static variables for them.

kind regards,

Jos ;-)
Jan 7 '08 #11
JosAH
11,448 Recognized Expert MVP
Maybe it's my background (math) but I usually find recursion easier to write and understand than iteration.
Let's shake hands but the way I read the question was about a non recursive
method and I'm also from the lazy bones camp and I think it's much easier
to cache stuff manipulated in the insert method than to set up explicit stacks
and/or trying to be clever with pointer fiddling etc. Recursive methods are much
easier to handle and implement though; I agree.

kind regards,

Jos
Jan 7 '08 #12
BigDaddyLH
1,216 Recognized Expert Top Contributor
Let's shake hands but the way I read the question was ...
Hear, hear. Now if we weren't on far sides of the world, I would say that calls for a beer!
Jan 7 '08 #13
JosAH
11,448 Recognized Expert MVP
Hear, hear. Now if we weren't on far sides of the world, I would say that calls for a beer!
Me too! No problem though, distance is just a figment of people's imagination and
we can solve this the mathematical way: I buy and drink your beer as well ;-)

kind regards,

Jos
Jan 7 '08 #14
r035198x
13,262 MVP
Me too! No problem though, distance is just a figment of people's imagination and
we can solve this the mathematical way: I buy and drink your beer as well ;-)

kind regards,

Jos
Public drinking is not allowed in the public forums.
Admin.
Jan 8 '08 #15
JosAH
11,448 Recognized Expert MVP
Public drinking is not allowed in the public forums.
Admin.
I wore a brown paper bag over my head so there was nothing public about it. I
looked and acted just like any other law obedient citizen.

kind regards,

Jos ;-)
Jan 8 '08 #16
AceKnocks
14 New Member
Expand|Select|Wrap|Line Numbers
  1. static Node root;
  2. static int countNode;
  3. ...
  4.  
  5. public BSTree() {
  6.     root = null;
  7. }
  8. ...
  9. public int size () {
  10.     return countNode;
  11. }
  12.  
  13.  
I just noticed that the root and the countNode (tree size) fields are static. What happens when you have another tree?
Those variables are static because trees themselves don't move either; when will
people ever learn ...

kind regards,

Jos ;-)
Thanks Jos for defending the objective. In this problem we were not assigned to make multiple BSTrees, rather just one tree which would have all these functions. :)

As far as writing a non-recursive (loop-iterative) height function is concerned, I could not come up with any and therefore implemented an overridden recursive function in the same class and called that recursive function from this non-recursive function.

I know that wasn't what I was supposed to do but I didnt have any bright ideas until the very last minute of my submission. Time for a compromise..eh
Jan 8 '08 #17
BigDaddyLH
1,216 Recognized Expert Top Contributor
Thanks Jos for defending the objective. In this problem we were not assigned to make multiple BSTrees, rather just one tree which would have all these functions. :)
I would rethink that, if I were you. You are going out of your way to make your code less general. If you insist on having static data, then all the methods should be made static, and the constructor hidden, because you've given up on a class that is designed to be instantiated.
Jan 8 '08 #18

Sign in to post your reply or Sign up for a free account.

Similar topics

7
3670
by: pembed2003 | last post by:
Hi, I have a question about how to walk a binary tree. Suppose that I have this binary tree: 8 / \ 5 16 / \ / \ 3 7 9 22 / \ / \ / \
4
2142
by: Max | last post by:
Hi guys, did some searching on the topic, but can't find much more then just basic info on binary trees. I need to write a binary tree implementation so that it is always complete. In other words operations such as add and delete will not cause the completeness to break. Re-adding all of the elements to a brand new tree and wiping out the old one is not an option, so any sorting that I do must be in place. Does anyone know of a good...
4
9033
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if I had C / \ B D
15
5131
by: Foodbank | last post by:
Hi all, I'm trying to do a binary search and collect some stats from a text file in order to compare the processing times of this program (binary searching) versus an old program using linked lists. I'm totally new to binary searches by the way. Can anyone help me with the commented sections below? Much of the code such as functions and printfs has already been completed. Any help is greatly appreciated. Thanks,
19
8631
by: ramu | last post by:
Hi, I have, suppose 1000 numbers, in a file. I have to find out 5 largest numbers among them without sorting. Can you please give me an efficient idea to do this? My idea is to put those numbers into a binary tree and to find the largest numbers. How else can we do it? Regards
2
2284
by: eSolTec, Inc. 501(c)(3) | last post by:
Thank you in advance for any and all assistance. Is there a way to start, pause and resume a recurrsive search exactly where you left off, say in the registry programmatically? -- Michael Bragg, President eSolTec, Inc. a 501(C)(3) organization MS Authorized MAR looking for used laptops for developmentally disabled.
1
2962
by: hn.ft.pris | last post by:
I have the following code: Tree.h defines a simple binary search tree node structure ########## FILE Tree.h ################ #ifndef TREE_H #define TREE_H //using namespace std; template <typename Tclass Tree{ private: Tree<T*left;
9
15259
by: nishit.gupta | last post by:
Can somebody please help me for algorithm for postorder bst traversal without recursion. It should use stack. i am not able to implement it. thnx
2
14747
by: aemado | last post by:
I am writing a program that will evaluate expressions using binary trees. Most of the code has been provided, I just have to write the code for the class functions as listed in the header file. However, I am really new to recursion and trees...and this program uses public functions and private helper functions, which I am completely lost in. Here is the header file: struct CTNode { NodeType type; int operand; CTNode *left, *right; };
0
10174
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9998
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11608
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11379
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10705
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7450
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6362
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3566
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.