473,834 Members | 1,800 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 #1
17 16382
BigDaddyLH
1,216 Recognized Expert Top Contributor
Hint: methods are applied to objects. With your height method, you seem to only want to pass objects as arguments. Hmmm...
Jan 7 '08 #2
Ganon11
3,652 Recognized Expert Specialist
Most recursive methods dealing with trees can be written with some loops - try thinking of, in general, what your recursive calls would do, then try to mimic that with loops.
Jan 7 '08 #3
BigDaddyLH
1,216 Recognized Expert Top Contributor
Most recursive methods dealing with trees can be written with some loops - try thinking of, in general, what your recursive calls would do, then try to mimic that with loops.
I didn't see anywhere (other that the topic!) in the original post where the OP was required to write a height function that wasn't recursive, just one that worked!
Jan 7 '08 #4
Ganon11
3,652 Recognized Expert Specialist
Guess I read into that by the phrase "The objective requires that the height be implemented without using an argument." Most recursive functions have an argument, though I suppose you could implement the recursion without an argument. Then again, if you did so (at least the way I'm thinking) you may as well just use loops.
Jan 7 '08 #5
JosAH
11,448 Recognized Expert MVP
@OP: you keep a separate variable countNode to keep track of the number of
nodes in the tree. You can do similar things where you keep track of the depth
or height of a node in the nodes themselves. At every insert you can update a
separate variable treeHeight and return its value at any time. That way you don't
need any recursion nor arguments to methods and what else ...

kind regards,

Jos
Jan 7 '08 #6
BigDaddyLH
1,216 Recognized Expert Top Contributor
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.  
I just noticed that the root and the countNode (tree size) fields are static. What happens when you have another tree?
Jan 7 '08 #7
BigDaddyLH
1,216 Recognized Expert Top Contributor
@OP: you keep a separate variable countNode to keep track of the number of
nodes in the tree. You can do similar things where you keep track of the depth
or height of a node in the nodes themselves. At every insert you can update a
separate variable treeHeight and return its value at any time. That way you don't
need any recursion nor arguments to methods and what else ...

kind regards,

Jos
I'm from the compute-don't-cache school (of default behaviours). getSize is easy to write recursively (I hope this isn;t giving away the exercise!):
Expand|Select|Wrap|Line Numbers
  1. public int getSize () {
  2.     return _size(root);
  3. }
  4.  
  5. private static int _size(Node n) {
  6.     return n==null? 0 : _size(n.left) + _size(n.right);
  7. }
Method getHeight is just as easy to write recursively. (I think it's actually much harder to write iteratively, since it is not a simple tail recursion.)

Maybe it's my background (math) but I usually find recursion easier to write and understand than iteration.
Jan 7 '08 #8
JosAH
11,448 Recognized Expert MVP
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.  
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 ;-)
Jan 7 '08 #9
BigDaddyLH
1,216 Recognized Expert Top Contributor
Those variables are static because trees themselves don't move either; when will
people ever learn ...

kind regards,

Jos ;-)
I must have been thinking of Ents
Jan 7 '08 #10

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

Similar topics

7
3658
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
2138
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
9024
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
5107
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
8597
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
2279
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
2957
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
15255
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
14733
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
9800
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
9651
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
10800
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
10225
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...
1
7762
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6960
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
5800
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4429
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3987
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.