Avl tree height
How do you get the height of a node in an avl tree? I understand how to balance, but I'm not sure about height. Say I have the following tree, what is the height of each node?
5
3 7
1 4 6 8
0 2
This would help me immensely. I can't balance them until I understand how to compute height!!! Any other helpful hints, such as sample height calculation code, would be helpful too!
Assuming the height of a node is the longest path down its children to a leaf, the height is recursively defined as the minimum of the heights of its children plus one, or 0 if the node has no children. The height of the tree would then be the height of the root node.
What does this have to do with Java?
Similar Messages
-
How to create input text of the node in AVL tree
Hi experts,
I create a simple AVL tree to display the sales order items, just two classes for one relationship. Like the left part on the screen in this program "DEMO_ABAP_OBJECTS_CONTROLS".
I want to let the node of the second class be maintained serial no., somthing like input field behind the node or double click the node, then show up the input field on another space on the same screen.
And there is a button on screen, I can do some check for the text of input field when pressing the button. If the input data is wrong , then show up the error message.
I have searched BCALV* in SE38, but i don't see anything helpful.
Plz give me some advice, thanks a lot!!
Regards,
ClaireTo Kunjal and Uwe,
My AVL tree is declared like this:
Data: tree TYPE REF TO cl_gui_simple_tree.
The class is not "cl_gui_alv_tree" , so I can not use the code.
The code I create the node is the follwing:
CALL METHOD tree->add_nodes
EXPORTING table_structure_name = 'ABDEMONODE'
node_table = node_table.
And I looked the program that Uwe wrote, the tree is declared in class cl_gui_alv_tree, too.
I want to double click the node and appear a field that can be inputed text.
Is there any other way to do this with the class cl_gui_simple_tree?
Thanks for the advence help.
Claire -
Can anyone help, I am not being deliverately stupid? I can create an avl tree, and I can create a shared memory area, but how do I put an AVL tree into the shared memory area?
You are probably creating the nodes of the tree using malloc.
Malloc is just handing you an area of memory. You already
have a block of memory, which is the shared memory block.
If you go to the part of the AVL program that you already have
and replace the malloc calls with calls to a routine that you
will write to give you blocks of your shared memory then you
are golden.
However, note that you may also have other details to take
care of such as making sure that the programs with which you
are sharing the memory block does not try to read or write the
block at the same time as someone else is using the block.
You can use a mutex, semaphore, or readers/writer lock for this
purpose. -
Help AVL Tree in JAVA code (remove) question-answer
Hi,
everyone. I have question.
I want codes in Java for AVL Tree.
I but must have remove methods or choose elements.
It`s main for me.
If you know, please write in code JAVA or contact e-mail.
or link to page or if you have self code.
thanks,
regards
[email protected]I have a better idea.
Why don't you try to do it yourself, and when you get stuck, post your code and details of what difficulty you're having.
When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read. -
hi iam not able to get the binary tree and avl tree in swings please any one help me
thanks in advanceHi Rastabot.
If you look closely, it's not that different after all.
In each step of your recursion you need to do two things: decide whether to keep recursing, and decide what to return to the previous recursive call.
If you are trying to traverse your entire tree, then your logic to determine when to recurse and when not to is exactly the same as your example.
What you want to return each time is the number of operators in and below the node in the tree. One useful property of such an expression tree is that all the operands become leaves of the tree, and all other tree nodes are operators. Therefore, if the current node is a leaf node (your subTree == null case in your example), then that node is not an operator and has no operators below it in the tree, therefore you can return zero as the number of operators in or below that node. On the other hand, if the node is not a leaf node (your else case) then it must be an operator, and therefore you would return 1 (for that operator) plus the number of operators in each subtree below that node.
This is very similar to what you have already posted - mostly, where you have strings you need to replace with integer equivalents.
I can help with this if you need.
Mac.
Edited by: Mac.Coombe on Apr 30, 2009 11:00 PM - made explanation a little clearer -
I am implementing an AVL tree for school assignment.
Everything has been smooth except for remove()method.
There are many different ways to implement this method, and the it is difficult to debug.
I have 5 hours left till the assignment is due, so I hope if anyone has any good examples on the remove() of AVL tree, please let me know. I have tried most links on Google and Google Code Search, but none of them suite my needs. Many of them use an extra datstructue such as queue or bitmap to do it, and some of them are too long and redundant.
My code is in reference to Weiss' Data Structure and Algorithm in Java book.
So basically I am looking for a hint on solving the problem or easy-to-read pseduoCode if possible.
Thank you and please reply as soon as you can because my time is running outHi, I'm using DefaultMutableTreeNode. On detecting a condition, I'm trying to remove a node under my root along with its children using removeNodeFromParent(); My appln just freezes and it doesn't refresh. The same code used to work with jvm_1.3.1 and all I did waz just upgrade it to 1.4.1_03; This is happening on a RedHat 9.0 Linux platform (if this matters). I tried catching Exception & Error - nothin' gets printed out. This is the snippet.
DefaultTreeModel model= (DefaultTreeModel) gethardwareTree().getModel();
HardwareTreeNode node= (HardwareTreeNode) model.getRoot();
Enumeration enumChildren = node.children();
ArrayList nodeList = new ArrayList();
// This is done to avoid using Enumeration
// Enumeration is not elegant in handling removal from its collection
while (enumChildren.hasMoreElements())
nodeList.add(enumChildren.nextElement());
Iterator rootChildren = nodeList.iterator();
while (rootChildren.hasNext())
// HardwareTreeNode is extended from DefaultMutableTreeNode
HardwareTreeNode hostNode = (HardwareTreeNode) rootChildren.next();
HardwareTreeNodeInfo currentInfo= hostNode.getTreeNode();
try {
// The following sys.out does get printed System.out.println("About to Remove: "+hostNode);
model.removeNodeFromParent(hostNode);
// The following sys.out doesn't get printed and it hangs
System.out.println("Removed: "+hostNode);
catch (Exception ex)//ArrayIndexOutOfBounds
System.out.println(ex);
Code once - use it anywhere - unfortunately didn't work??
Pls. post Ur Xperienced thoughts. -
How to use GUI to display AVL tree.-Urgent
Hi,
I implemented the insertion of the AVL Tree, it worked fine. but i do not know how to use the GUI to display the tree befor and after the insertion.
Could you please help me,
thanks,Have you considered using JTree?
-
Hi;
when I try to reblance a tree to AVL tree, But I find i can get two different result, but they all satisfy the difinition of AVL, do you think they are ok? ThanksYou don't give many details in which sense the two results are different, do you?
A definition of an AVL tree: it is a binary search tree where
a) each vertex is a leaf, or
b) each vertex has only one descendant, which is a leaf, or
c) each vertex has two descendants; the depths of the subtrees, whose roots are the descendats, differ maximum by 1
The point c) provides two options: either depth of the left subtree is greater or equal than the depth of right subtree, or vice versa. You could have two special cases where depth of all the left subtrees is always greater or equal than the depth of the right ones or the other way around. Quite apparently, you can have many more results, if you mix the right/left preference. This, however, is not important - the only important thing is the the depth of subtrees. If you think why, it is because it secures you that in a tree of n vertices your search will always be O(log n). -
Hi all,
I am interested in an AVL tree implementation in Java. I prefer it to be Open Source. Efficiency is my main concern, although a readable code would be appreciated.
The question is if it exist a standard implementation or an implementation you know it is stable and efficient.
thank you in advance,prometheuzz wrote:
The TreeSet and TreeMap implementations from the java.util package are backed up by a red-black tree. So those classes have the same characteristics as an AVL tree: they're self balancing, and insertions and lookups are O(log(n)) where n is the total number of nodes in your tree.
So, as far as I see, you can use those classes. If not, please explain why you need an AVL tree instead of a proven/reliable class already present in the standard API.Thank you for the answer.
to be honest, in the past, I rejected the idea of using TreeMap or TreeSet, but I fail to understand (or remember) why.
The only reason I see at the moment is that I would like the tree notion of child nodes etc, although I can live without that given that I have an efficient implementation in zero-time. :)
The use of AVL trees is not needed in the implementation, it is just an offspring of the theoretical complexity analysis of what I am about to implement. -
hey guys. I have the following insert method that i made for a BST but now i need to convert my inser and delete methods to work with AVL trees. I have created an extra variable in my node class called "balance" to keep track of every nodes balance. I have also created the method names getBalance and setBalance to get and set new balances.
this is my inser method
//Insert val into the BSt - does nothing if val is already in the tree
public void insert(String val)
root = rInsert(root, val);
private StringAVLNode rInsert(StringAVLNode n, String str)
if(n!=null && n.getItem().compareTo(str)==0)//if its a duplicate
{//do nothing
else if(n==null) //if insertion point is found
//create a new node in the insertion point that is found
StringAVLNode nd = new StringAVLNode(str, null, null);
n = nd;
else if(str.compareTo(n.getItem())<0)//if insertion point is to the left
n.setLeft(rInsert(n.getLeft(), str));
else // insertion point is to the right
n.setRight(rInsert(n.getRight(), str));
return n; //return the new inserted node
}i need to convert it into an AVL insert so i have to check the old balance before inserting and then check the new balance after inserting and make the proper rotation to balance the tree if its out of balance
a node balance value of 1 means the subtree is a little heave and a balance of -1 means the left subtree is a litle heavy. 0 means the node is completely balanced. if the value is greater than 1 on the righ side then the right side is out of balance so it has to be rotated left to balance itself and if the value is less than -1, then the left side is out of balance and needs to be rotated to the right.
i am not exactly sure where i would update the balance for the nodes during my insert method. I have done the following so far but i am completly stuck right now and clueless as to what to do.
private StringAVLNode rInsert(StringAVLNode n, String str)
if(n!=null && n.getItem().compareTo(str)==0)//if its a duplicate
{//do nothing
else if(n==null) //if insertion point is found
//create a new node in the insertion point that is found
StringAVLNode nd = new StringAVLNode(str, null, null);
n = nd;
else if(str.compareTo(n.getItem())<0)//if insertion point is to the left
int oldBalance = n.getLeft().getBalance();
n.setLeft(rInsert(n.getLeft(), str));
int newBalance = n.getLeft().getBalance();
else // insertion point is to the right
int oldBalance = n.getRight().getBalance();
n.setRight(rInsert(n.getRight(), str));
int newBalance = n.getRight().getBalance();
return n; //return the new inserted node
}i also have to consider double rotations. I know how they work on paper but can't seem to put it in code.
any help would be nice.AVL trees are always balanced because they guarantee O(logn) retrieval. A balanced binary search tree will also be O(logn) retrieval. Thus, you could state that as long as a binary search tree is balanced it will have the same performance as an AVL tree.
-
Need Tree.height as currently expanded
Okay, here's what I'm doing. I have an <mx:List> who
uses an <mx:Tree> component as the item renderer. I've gotten
that to work just fine; the problem I'm having is with resizing the
component to the current shape of the tree. I know how to do a
resize and I have the list's variableRowHeight property set to
true, so it does resize and work generally. All I'm trying to do is
get the itemRenderer component to resize itself to
Tree.currentExpandedHeight unfortunately that is an
imaginary property. Does anyone else know of how to find that out?
Who can make my imagination reality?
I just need to find the
current vertical height of a tree component as it sits fully
expanded or half expanded, or fully collapsed. I'll then resize on
the fly as it expands and contracts.there is a private function in the tree.as class:
private function getVisibleChildrenCount(item:Object):int
that I can use by multiplying how many children there are by
how tall each item "physically" displays on the screen as, but I
want to get that publicly. I don't want to go about hacking the
tree.as code, that's poor form in the highest. Does anybody else
have any ideas...
please? -
hi all,
i have created a tree in my BSP page and i hard code the content of the tree like
CLEAR wa_tab.
level 1 - Knowledge and help
wa_tab-treeid = 'support_application'.
wa_tab-parentid = ''.
wa_tab-childid = 'HELP'.
wa_tab-text = 'Self Help'.
APPEND wa_tab TO gt_tab.
but i want to make the size of tree higher, i coding like below
<htmlb:tree title = "<%= otr(/SPN/SMB/VAR05P01_04) %>"
showTitle = "true"
id = "support_application"
table2 = "<%= gt_tab %>"
width = "100%"
height = "120%" />
but nothing happened ,
i added a empty line in the tree table but there is a icon before the empty tree node ,
who can give me a hand ?a htmlb:tree occupies as much space as required to render the nodes, if you want it to occupy more space (height) you have to set some nodes expanded. the height property of the tree dosent make any difference
Regards
Raja -
the line tree.addElement( new Integer(3)); gives me type expected error. why does this happen?
import jds.collection.AVLTree;
public class printOut extends AVLTree
public static void main(String args[])
AVLTree tree = new AVLTree(test);
tree.addElement( new Integer(3));
Enumeration e = tree.elements()
while (e.hasMoreElements())
data.setElementAt(e.nextElement(), i++)
System.out.println(tree.toString());
}import jds.collection.AVLTree;
public class printOut extends AVLTree { // Why do you extend? You're just using this class. You're not even overriding a single method.
public static void main(String args[]) {
AVLTree tree = new AVLTree(test); // code belongs into method body
tree.addElement(new Integer(3));
Enumeration e = tree.elements();
while(e.hasMoreElements()) {
data.setElementAt(e.nextElement(), i++); // Don't understand what you are trying to do here
System.out.println(tree.toString()); // Where does i come from? Do you really want to print the whole tree? -
the line tree.addElement( new Integer(3)); gives me type expected error. why does this happen?
import jds.collection.AVLTree;
public class printOut extends AVLTree
public static void main(String args[])
AVLTree tree = new AVLTree(test);
tree.addElement( new Integer(3));
Enumeration e = tree.elements()
while (e.hasMoreElements())
data.setElementAt(e.nextElement(), i++)
System.out.println(tree.toString());
}What is the type of test?
-
Binary Tree search and print methods
Hello, I'm trying to create a binary tree from inputs of a user. I believe I have the tree set up right because it shows no errors, but I'm getting an error message with a line of code. I cannot figure out what I am doing wrong. Also, I need to create a print method, which prints the tree's entries and a search method which would search the tree for certain record.
public class TreeNode
public static String empName = null;
public static int empNumber;
public static String nextRec = null;
TreeNode left;
String Name;
int Number;
TreeNode right;
public static void main(String[] args)
VRead in = new VRead();
VWrite out = new VWrite();
System.out.println("Enter Choice: ");
System.out.println("A: Enter Employee Information.");
System.out.println("B: Search For Employee.");
System.out.println("C: Print Entire Tree.");
System.out.println("D: Exit.");
System.out.println("_______________________________");
char command = in.readChar();
System.out.println();
switch (command)
case 'A':
case 'a':
inputInfo(in, out);
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
System.exit(0);
break;
public static void inputInfo(VRead in, VWrite out)
out.write("Enter Employee Name: ");
empName = in.readString();
out.write("Enter Employee Number: ");
empNumber = in.readInt();
System.out.println();
System.out.println();
System.out.println("Enter Choice: ");
System.out.println("A: Enter Employee Information.");
System.out.println("B: Search For Employee.");
System.out.println("C: Print Entire Tree.");
System.out.println("D: Exit.");
System.out.println("_______________________________");
char command = in.readChar();
System.out.println();
switch (command)
case 'A':
case 'a':
inputInfo(in, out);
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
System.exit(0);
break;
public TreeNode(String empName, int empNumber)
Name = empName;
Number = empNumber;
left = null;
right = null;
public class Tree
TreeNode Root;
public void Tree(String RootNode)
// Errors come from next line
Root = new TreeNode(RootNode, Name, Number);
public void Insert(String Name, int Number)
InsertNode(Root, Name, Number);
public void InsertNode(TreeNode t, String empName, int empNumber)
if (t == null)
t = new TreeNode(empName, empNumber);
else
if (empName.compareTo(t.Name) < 0)
InsertNode(t.left, empName, empNumber);
else if (empName.compareTo(t.Name) > 0)
InsertNode(t.right, empName, empNumber);
else if (empName.compareTo(t.Name) == 0)
System.out.println("Entered node that was already in Tree");
}im sure its something simple, i seem to always look over the small stuff. But i could really use some help on the print and search method tooJust having a quick look over it, and it looks like you are trying to add an extra argument in the TreeNode() method (unless there is a bit of overloading and there is a second treenode method in there) As it is TreeNode only accepts two argumets you have 3
As for printing the tree you would need to flatten it, that is an in order traversal of the tree.
FWIW
I just finished a project at uni that involved at frist writing a BST and then an AVL tree. the full point of these things seems to be to keep students awake at night*
*Before anyone flames, it's a joke
G
Maybe you are looking for
-
Using Adobe Bridge with Photoshop Elements
I have an iMAC with iLife 08. I take photos in RAW format with a Nikon camera. I have been editing photos this way: After uploading photos to iPhoto, export them as jpg to a new folder on the desktop, external HD or wherever. I open Photoshop Element
-
Error in CHARM configuration to move JAVA objects 'The project is not relea
Hi, I have BI 7.0 (ABAP + JAVA) landscape (i.e. CBD, CBQ and CBP) on SPS12 and SolMan 7.0 (SMD) on SPS14. My goal is to move both ABAP and JAVA transports through CHARM. I performed following tasks: 1. Configured TMS by selecting CBD as Transport D
-
Java.lang.OutOfMemoryError Exception for data more than 20k rows
Hi There, We are evaluating Coherence for our requirements and I am quite impressed with filtering, near cache, etc We are running on Windows XP, 3GB RAM, jdk1.6.0_04 and tests are simple – 2 cache instances and one instance of ExtendTcpCacheService
-
Hi All, I have build a xml interface for a java application. I parse the xml files using dom parser, get the data and pass it to the java application. I know that DOM builds a in memory tree of the xml file. Will this degrade the performance of my ap
-
Email won't login suddenly-again
I'm sure this has been posted on, but the search function isn't giving me what I need. Apologies, but it is an emergency-my airline ticket home is in this account and I at least need to forward it to one I can check somewhere else, as well as other t