Binary Tree Question
Ok, I am making a binary tree. I have a question for my insert method. Firstly, I can't find out why the root node is inserted more than once in the tree. Also, I am having trouble with connecting the nodes that I insert to the tree. I can attach modes to root just fine, but I can't find out how to attach nodes to the existing nodes that are already attached to the tree. When I insert a node that meets the criteria of an already existing node, it replaces the node instead of getting attached to it. The answer is probably trivial, but I can't find it. Here is my insert method.
public void insert(T obj) {
int _result1;
int _result2;
//TODO: Implement Q1 here
if(isEmpty() == true){
_root = createNode(obj, null, null, null);
System.out.println("The root inserted is " + _root.element());
insert(obj);
_node = createNode(obj, _root, null, null);
_result1 = _node.element().compareTo(_root.element());
if(_result1 < 0){
if(_node.isInternal() == true){
_current = (BTreeNode<T>) _node2.element();
_result2 = _current.element().compareTo(_current.getParent().element());
//System.out.println("The current element is " + _current.element());
if(_result2 < 0){
_node1.getLeft();
_current = _node1.getLeft();
else{
_node1.getRight();
_current = _node1.getRight();
if(_node1.hasLeft() == true){
_node1.getLeft();
_current = _node1.getLeft();
else{
_current.setLeft(_node1);
_current = _node2;
else{
_node1 = createNode(obj, _node, null, null);
_node.setLeft(_node1);
_node1.setParent(_node);
System.out.println("The parent of the left node " + _node.element() + " is " + _node.getParent().element());
_root.setLeft(_node1);
_current = _node1;
//System.out.println("The current element is " + _node.element());
else{
if(_node.isInternal() == true){
_current = (BTreeNode<T>) _current.element();
_result2 = _current.element().compareTo(_current.getParent().element());
//System.out.println("The current element is " +_current.element());
if(_result2 < 0){
_node1.getLeft();
_current = _node1.getLeft();
else{
_node1.getRight();
_current = _node1.getRight();
if(_node1.hasRight() == true){
_node1.getRight();
_current = _node1.getRight();
else{
_current.setLeft(_node1);
_current = _node1;
else{
_node1 = createNode(obj, _node, null, null);
_node.setRight(_node1);
_node1.setParent(_node);
//_current = _node1;
System.out.println("The parent of the right node " + _node.element() + " is " + _node.getParent().element());
_root.setRight(_node1);
_current = _node1;
//System.out.println("The current element is " + _current.element());
}The output I get is:
The root inserted is 6
The parent of the right node 6 is 6
The parent of the right node 6 is 6 ** I can't figure out why the root is inserted two extra times**
The parent of the left node 3 is 6
The parent of the right node 11 is 6
The parent of the right node 12 is 6 ** this node should be attaching to 11 instead of replacing it **
The parent of the right node 8 is 6
The parent of the right node 9 is 6
The parent of the right node 10 is 6
The parent of the right node 7 is 6
preorder :(6 (3 )(7 ))
postorder:(( 3) ( 7) 6)
IMO, your insert method is way too complicated.
Have a look at this pseudo code: that's all it takes to insert nodes in a BT:
class Tree<T extends Comparable<T>> {
private Node root;
public void insert(T obj) {
'newNode' <- a new Node('obj') instance
IF 'root' equals null
let 'root' be the 'newNode'
ELSE
insert('root', 'newNode')
END IF
public void insert(Node parent, Node newNode) {
IF 'parent' is less than 'newNode'
IF the left child of 'parent' is null
let 'newNode' be the left child of 'parent'
ELSE
make a recursive call here: insert('???', 'newNode')
END IF
ELSE
IF the right child of 'parent' is null
let 'newNode' be the right child of 'parent'
ELSE
make a recursive call here: insert('???', 'newNode')
END IF
END IF
}
Similar Messages
-
Basic binary search tree question
Hi,
I was just wondering, if there's a binary search tree that holds objects can the binary search tree be based on any of the attributes in those objects.
So for example say we have a Person object and it has the attributes name, age, and height. Can we make a binary search tree based on the age or a search tree based on just the height.
And lastly how would that be done in the comparable method.
Thanks.Of course it depends on what (and whether) the Person class implements for Comparable. If you want to base the tree on the default comparison (i.e., the one that compareTo does) then you don't need a separate Comparator.
When you write your binary tree implementation, it's wise to make it smart enough to either take a Comparator, or to use the default comparison (if the objects being tracked implement Comparable).
Note that Comparators and Comparable have nothing to do with trees per se. It's not like a tree necessarily needs one or the other. It's simply very smart to use the existing Java framework to determine an order among objects. -
Complete Binary Tree Illustration Question
Hello I am trying to illustrate the following integers as a complete binary tree:
20, 12, 17, 36, 25, 49, 52, 65, 42, 35, 71, 43, 54
I wanted to ask if in inorder to create the complete binary tree, do I need to start in the very middle (52) then half the left and right side and continue this process until complete? eg:
52
36 71
Or do I start from the begining of the array, as below:
20
12 36
17Thanks for the answers guys!
Paul based on what you said, does this then look correct to you or have I got the wrong idea?:
20
12 36
17 25 49
35 42 52
43 65
54 71 -
I have been struggling for a tree search problem for a good while. Now I decide to ask you experts for a better solution :-).
Given a binary tree A. We know that every Node of A has two pointers. Leaves of A can be tested by if(node.right = =node). Namely, The right pointer of every leaf node points to itself. (The left pointer points to the node sits on the left side of the leaf in the same depth. and the leafmost node points to the root. I do no think this information is important, am i right?).
Tree B has a similar structure.
The node used for both A and B.
Node{
Node left;
Node right;
My question is how to test if tree B is a subtree of A and if it is, returns the node in A that corresponds to the root of B. otherwise, return null.
So, the method should look like:
public Node search(Node rootOfA, Node rootOfB){
I know a simple recursive fuction can do the job. The question is all about the effciency....
I am wonderring if this is some kind of well-researched problem and if there has been a classical solution.
Anyone knows of that? Any friend can give a sound solution?
Thank you all in advance.
Jason
Message was edited by:
since81I'm not too sure if this would help but there goes.
I think a recursive function will be the easiest to implement (but not the most efficient). In terms of recursive function if you really want to add performance. You could implement your own stack and replace the recursive function with the use of this stack (since really the benefit of recursive function is that it manages its own stack). A non-recursive function with customized well implemented stack will be much more efficient but your code will become more ugly too (due to so many things to keep track of).
Is tree B a separate instance of the binary tree? If yes then how can Tree B be a subset/subtree of tree A (since they are two separate "trees" or instances of the binary tree). If you wish to compare the data /object reference of Tree B's root node to that of Tree A's then the above method would be the most efficient according to my knowledge. You might have to use a Queue but I doubt it. Stack should be able to replace your recursive function to a better more efficient subroutine but you will have to manage using your own stack (as mentioned above). Your stack will behave similar to the recursive stack to keep track of the child/descendant/parent/root node and any other references that you may use otherwise.
:) -
Binary Tree in Java - ******URGENT********
HI,
i want to represent a binary tree in java. is there any way of doing that.
thanx
sraphsonHI,
i want to represent a binary tree in java. is there
e any way of doing that.
thanx
sraphsonFirst, what is a binary tree? Do you know how the binary tree looks like on puesdo code? How about a representation in terms of numbers? What is a tree? What is binary? The reason I ask is, what do you know about programming?
Asking to represent a binary tree in java seems like a question who doesn't know how it looks like in the first please. Believe me, I am one of them. I am not at this level yet. If you are taking a class that is teaching binary trees and you don't know how it looks like, go back to your notes.
Sounds harsh, but it is better to hear it from a person that doesn't know either then a boss that hired you because Computer Science was what you degree said. Yet, you don't know how to program?
Telling you will not help you learn. I can show you tutorials of trees would be start on where to learn.
HOW TO USE TREES (oops this is too simple, but it is a good example)
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
CS312 Data Structures and Analysis of Algorithms
(Here is a course about trees. Search and learn)
http://www.calstatela.edu/faculty/jmiller6/cs312-winter2003/index.htm -
Hi there
Do you have any suggestions about how to implement trees or binary trees in Java?
As far as I know there are already some libraries for that, but I don't know how to use them. Was trying to get some implementation examples but I'm still very confused.
How can I use for example:
removeChild(Tree t)
addChild(Tree t)
isLeaf()
Thanks in advanceLulu wrote:
Hi there
I have several questions about binary trees
Let's see, I use TreeMap to create them with the following code:
TreeMap treeMap = new TreeMap<Integer, String>();
treeMap.put("first", "Fruit");
treeMap.put("second","Orange");
treeMap.put("third", "Banana");
treeMap.put("fourth", "Apple");You've defined the map to hold integer keys and strings as values, yet you're trying to add string keys and string values to it: that won't work.
If this is a map how do I define if the data should go to the left or to the right of certain node?That is all done for you. In a TreeMap (using the no-args constructor), you can only store objects that are comparable to each other (so, they must implement the Comparable interface!). So the dirty work of deciding if the entry should be stored, or traversed, into the left or right subtree of a node, is all done behind the scenes.
Also note that TreeMap is not backed up by a binary tree, or a binary search tree, but by a red-black tree. A red-black tree is a self balancing binary tree structure.
Should I have dynamical keys so that they increase automatically when adding new data?
According to a webpage I should use Comparator(), is that to find the data in the tree and retrieve the key?
ThanksI am not sure what it is you want. I am under the impression that you have to write a binary tree (or a binary search tree) for a course for school/university. Is that correct? If so, then I don't think you're permitted to use a TreeMap, but you'll have to write your own classes. -
Binary tree using inorder traversal algorithm
I need to draw a Binary tree using Inorder traversal algorithm.. in java applets using rectangles and ellipse objects.. can anyone help me about this ? I will be really thankful to yu
I think this is my psychic Sunday, so here's my attempt at answering
this vaguely stated question. First have a look at this fine piece of
ASCII art:-------------------------------------------- ^ ^
| A T | | |
| | | root
---------L-----------------------R---------+ | v
| B | C | |
| | | |
| | | height
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
-------------------------------------------+ v
<--------------------width------------------->Suppose you have a rectangle 'width' wide and 'height' high. The root
of the tree can be drawn at position T and (if present), two lines can be
drawn to the positions L and R respectively. Now recursively call your
same method using the computed rectangle A and B for the left and
right subtrees L and R respectively.
kind regards,
Jos -
Putting words from a text file into a binary tree.
I am having problems figuring out how to do this.
the text file will have a sentence like this
Every one likes to play games.
My Dog tore up my apartment last night.
How old are you sir.I know how to put regular strings into a binary tree, but I don't know what to do in order to put these textfile strings into it.
I thought of using string tokenizer but I couldn't get that to work because the sentences are not a specific length, they can be any length. Can somebody give me some tips on what to use?
Thank youJulianJ wrote:
That will work?I'm sorry to tell you, that is a really bad question. Of course it won't work, because you did something else wrong. I have no idea what, but it's pretty certain that you haven't got everything right yet. (And that's nothing personal, it's just an observation about computer programming in general.) But don't let that stop you. And don't wait around for people to validate your ideas. Try it and see what happens. You won't break anything. And when it doesn't work, figure out why and carry on. -
Help loading a binary tree from file
Hi all,
So I am working on making a 20 question game using a binary tree. I have set it up so each time the user plays, if the computer cannot guess what they are thinking of, they tell the computer and it saves it. I am saving the tree in a text file recursively, in a format that looks something like this:
Do you use it outside?
a shovel
[null]
[null]
is it round?
a ball
[null]
[null]
a TV
[null]
[null]
The problem is now, I am having a very hard time rebuilding the tree when the user restarts the game. As you can see, the "{" indicates the beginning of a path and the "}" is the end. Can someone suggest a nice way to load this back up into my data structure? Thanks!!Cross-post here: [http://www.java-forums.org/java-2d/14237-help-loading-binary-tree-file.html]
Recommended looking into XML -
Hi, I have a class called DigitalTree that acts like a binary tree, storing nodes that each have a "key" which is a long value, and then puts each node into the tree in its correct place, binary tree style. I am trying to deep clone the tree, but for some reason my recursive cloning method isn't working. If anyone can see a problem in my code or has any tips for me, it would be greatly appreciated. Thanks.
public Object clone()
DigitalTree<E> treeClone = null;
try
treeClone = (DigitalTree<E>)super.clone();
catch(CloneNotSupportedException e)
throw new Error(e.toString());
cloneNodes(treeClone, this.root, treeClone.root);
return treeClone;
private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
if(treeClone.size == 0)
cloneNode = null;
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
else if(currentNode != null)
cloneNode = (Node<E>)currentNode.clone();
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
}In the Node class:
public Object clone()
Node<E> nodeClone = null;
try
nodeClone = (Node<E>)super.clone();
catch(CloneNotSupportedException e)
throw new Error(e.toString());
return nodeClone;
}Hello jssutton
Your question inspired me to try my own binary tree and cloning. My cloning algorithm is similar to yours but with one difference.
In my class Tree defined as:
class Tree<T extends Comparable>
I have:
private void deepCopyLeft(TreeNode<T> src, TreeNode<T> dest) {
if (src == null) return;
dest.mLeft = new TreeNode<T>(src.mValue);
deepCopyLeft(src.mLeft, dest.mLeft);
deepCopyRight(src.mRight, dest.mLeft);
private void deepCopyRight(TreeNode<T> src, TreeNode<T> dest) {
if (src == null) return;
dest.mRight = new TreeNode<T>(src.mValue);
deepCopyLeft(src.mLeft, dest.mRight);
deepCopyRight(src.mRight, dest.mRight);
public Tree<T> deepCopy() {
if (root == null) return new Tree<T>();
TreeNode<T> newRoot = new TreeNode<T>(root.mValue);
deepCopyLeft(root.mLeft, newRoot);
deepCopyRight(root.mRight, newRoot);
return new Tree<T>(newRoot);
}Its a similar recursive idea, but with 2 extra functions. I hope that helps. I don't have time right now to pinpoint the problem in your routine. Good luck. -
Traverse a binary tree from root to every branch
I have a couple of other questions. I need to get all the different combinations of a binary tree and store them into a data structure. For the example in the code below, the combinations would be:
1) Start, A1, A2, A3, B1, B2, B3
2) Start, A1, A2, B1, A3, B2, B3
3) Start, A1, A2, B1, B2, A3, B3
4) Start, A1, A2, B1, B2, B3, A3
5) Start, A1, B1, A2, A3, B2, B3
etc.
I understand that this is very similar to the preorder traversal, but preorder does not output the parent nodes another time when the node splits into a left and right node. Any suggestions?
* To change this template, choose Tools | Templates
* and open the template in the editor.
package binarytreetest;
import java.util.ArrayList;
import java.util.Iterator;
* @author vluong
public class BinaryTreeTest {
* @param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
int countA = 0;
int countB = 0;
ArrayList listA = new ArrayList();
ArrayList listB = new ArrayList();
listA.add("A1");
listA.add("A2");
listA.add("A3");
listB.add("B1");
listB.add("B2");
listB.add("B3");
//listB.add("B1");
Node root = new Node("START");
constructTree(root, countA, countB, listA, listB);
//printInOrder(root);
//printFromRoot(root);
public static class Node{
private Node left;
private Node right;
private String value;
public Node(String value){
this.value = value;
public static void constructTree(Node node, int countA, int countB, ArrayList listA, ArrayList listB){
if(countA < listA.size()){
if(node.left == null){
System.out.println("There is no left node. CountA is " + countA);
System.out.println("Created new node with value: " + listA.get(countA).toString() + " with parent, "
+ node.value);
System.out.println();
node.left = new Node(listA.get(countA).toString());
constructTree(node.left, countA+1, countB, listA, listB);
}else{
System.out.println("There is a left node. CountA + 1 is " + countA+1);
constructTree(node.left, countA+1, countB, listA, listB);
if(countB < listB.size()){
if(node.right == null){
System.out.println("There is no right node. CountB is " + countB);
System.out.println("Created new node with value: " + listB.get(countB).toString() + " with parent, "
+ node.value);
System.out.println();
node.right = new Node(listB.get(countB).toString());
constructTree(node.right, countA, countB+1, listA, listB);
}else{
System.out.println("There is a right node. CountB + 1 is " + countB+1);
constructTree(node.right, countA, countB+1, listA, listB);
}My second question is, if I need to add another list (listC) and find all the combinations of List A, listB and list C, is it correct to define the node class as
public static class Node{
private Node left;
private Node mid;
private Node right;
private String value;
public Node(String value){
this.value = value;
}Node left = listA, Node mid = listB, Node right = listC
The code for the 3 lists is below.
3 lists (A, B, C):
* To change this template, choose Tools | Templates
* and open the template in the editor.
package binarytreetest;
import java.util.ArrayList;
* @author vluong
public class BinaryTreeTest {
* @param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
insert(root, "A1");
insert(root, "A2");
insert(root, "B1");
insert(root, "B2");
insert(root, "A2");
int countA = 0;
int countB = 0;
int countC = 0;
ArrayList listA = new ArrayList();
ArrayList listB = new ArrayList();
ArrayList listC = new ArrayList();
listA.add("A1");
listA.add("A2");
//listA.add("A3");
listB.add("B1");
listB.add("B2");
//listB.add("B3");
//listB.add("B1");
listC.add("C1");
listC.add("C2");
Node root = new Node("START");
constructTree(root, countA, countB, countC, listA, listB, listC);
//ConstructTree(root, countA, countB, listA, listB);
//ConstructTree(root, countA, countB, listA, listB);
printInOrder(root);
//printFromRoot(root);
public static class Node{
private Node left;
private Node mid;
private Node right;
private String value;
public Node(String value){
this.value = value;
public static void constructTree(Node node, int countA, int countB, int countC, ArrayList listA, ArrayList listB, ArrayList listC){
if(countA < listA.size()){
if(node.left == null){
System.out.println("There is no left node. CountA is " + countA);
System.out.println("Created new node with value: " + listA.get(countA).toString() + " with parent, "
+ node.value);
System.out.println();
node.left = new Node(listA.get(countA).toString());
constructTree(node.left, countA+1, countB, countC, listA, listB, listC);
}else{
System.out.println("There is a left node. CountA + 1 is " + countA+1);
constructTree(node.left, countA+1, countB, countC, listA, listB, listC);
if(countB < listB.size()){
if(node.mid == null){
System.out.println("There is no mid node. CountB is " + countB);
System.out.println("Created new node with value: " + listB.get(countB).toString() + " with parent, "
+ node.value);
System.out.println();
node.mid = new Node(listB.get(countB).toString());
constructTree(node.mid, countA, countB+1, countC, listA, listB, listC);
}else{
System.out.println("There is a right node. CountB + 1 is " + countB+1);
constructTree(node.mid, countA, countB+1, countC, listA, listB, listC);
if(countC < listC.size()){
if(node.right == null){
System.out.println("There is no right node. CountC is " + countC);
System.out.println("Created new node with value: " + listC.get(countC).toString() + " with parent, "
+ node.value);
System.out.println();
node.right = new Node(listC.get(countC).toString());
constructTree(node.right, countA, countB, countC+1, listA, listB, listC);
}else{
System.out.println("There is a right node. CountC + 1 is " + countC+1);
constructTree(node.mid, countA, countB, countC+1, listA, listB, listC);
}Thank you in advance!It looks to me like you are interleaving two lists. It looks like you are doing this while leaving the two subsequences in their original order.
If that is in fact what you are doing, then this is just a combinatorics problem. Here is psuedo code (NOT java!)
List path = new List();
show(List A, int a, List B, int b, path){
if(a >= A.length() && b >= b.length()){
spew(path);
} else {
if(a < A.length()){path.push(A[a]); show(A,a+1,B,b,); path.pop();}
if(b < B.length()){path.push(B); show(A,a,B,b+1,); path.pop();}
show(A, 0, B, 0);
In order to interleave 3 lists, you would add C and c arguments to the function and you would add one more line in the else block. -
How to crossover this binary tree..?
You can view detail http://www.codeguru.com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
[nha khoa|http://www.sieuthi77.com/main/nhakhoa.html] .com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
I have these classes which model a tree (binary). the thing is i cant figure out how i can set the elements of individual nodes in that tree. i can get individual elements but i cannot set them due to the strucutre of the tree and how it is implemented. The changes that I make to these classes should be as less as possible, because i have an algorithm which generates the tree structure randomly, plus i can evaluate the tree easily by using recursion. The only left thing to do is CROSSOVER but how?!?
here are the classes which model my binary tree:
Code:
public abstract class Node implements Cloneable{
abstract double evaluate(VariableInput v);
abstract String print();
abstract int getNumberOfNodes();
abstract ArrayList<Object> getChildren();
@Override
public Node clone(){
Node copy;
try {
copy = (Node) super.clone();
} catch (CloneNotSupportedException unexpected) {
throw new AssertionError(unexpected);
//In an actual implementation of this pattern you might now change references to
//the expensive to produce parts from the copies that are held inside the prototype.
return copy;
Code:
public class UnaryNode extends Node {
private UnaryFunction operator;
private Node left;
public UnaryNode(UnaryFunction op, Node terminal) {
operator = op;
this.left = terminal;
public String print(){
String r = "(" + operator.toString()+ " " + left.print() + ")";
return r;
void setLeft(Node left) {
this.left = left;
@Override
int getNumberOfNodes() {
return 1 + left.getNumberOfNodes();
Node getLeft() {
return left;
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(this);
arr.addAll(left.getChildren());
return arr;
Code:
public class BinaryNode extends Node {
private BinaryFunction operator;
private Node left;
private Node right;
public BinaryNode(BinaryFunction op, Node left, Node right) {
operator = op;
this.left = left;
this.right = right;
public String print(){
String r = "(" + operator.toString()+ " " + left.print() + " " + right.print()+")";
return r;
public void setLeft(Node left){
this.left = left;
public void setRight(Node right){
this.right = right;
@Override
int getNumberOfNodes() {
return 1 + left.getNumberOfNodes() + right.getNumberOfNodes();
Node getRight() {
return right;
Node getLeft() {
return left;
@Override
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(this);
arr.addAll(left.getChildren());
arr.addAll(right.getChildren());
return arr;
public class NumericNode extends Node{
private double value;
public NumericNode(double v){
value = v;
@Override
double evaluate(VariableInput c) {
return value;
public String print(){
String r = "" + value;
return r;
@Override
int getNumberOfNodes() {
return 1;
@Override
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(new NumericNode(value));
return arr;
}p.s. I have this get children method which return a list of REFERENCES to all the nodes in the tree, but if i change any of them it wont have an effect to the tree itself because they are references.
Any ideas or codes will be much appreciated. Thanks!What? Changes to what a node is referencing will be reflected in the tree, unless your getChildren is returning a copy, like in NumericNode.
Kaj -
Need Help with a String Binary Tree
Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
plssss... someone pls help me on this
here is my code now:
// TreeApp.java
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*; // for I/O
import java.util.*; // for Stack class
import java.lang.Integer; // for parseInt()
class Node
//public int iData; // data item (key)
public String iData;
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
} // end class Node
class Tree
private Node root; // first node of tree
public Tree() // constructor
{ root = null; } // no nodes in tree yet
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no match,
if(key < current.iData) // go left?
current = current.leftChild;
else // or go right?
current = current.rightChild;
if(current == null) // if no child,
return null; // didn't find it
return current; // found it
} // end find()
public Node recfind(int key, Node cur)
if (cur == null) return null;
else if (key < cur.iData) return(recfind(key, cur.leftChild));
else if (key > cur.iData) return (recfind(key, cur.rightChild));
else return(cur);
public Node find2(int key)
return recfind(key, root);
public void insert(int id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public void insert(String id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
//if(id < current.iData) // go left?
if(id.compareTo(current.iData)>0)
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public Node betterinsert(int id, double dd)
// No duplicates allowed
Node return_val = null;
if(root==null) { // no node in root
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
root = newNode;
return_val = root;
else // root occupied
Node current = root; // start at root
Node parent;
while(current != null)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.leftChild = newNode;
} // end if go left
else if (id > current.iData) // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.rightChild = newNode;
} // end else go right
else current = null; // duplicate found
} // end while
} // end else not root
return return_val;
} // end insert()
public boolean delete(int key) // delete node with given key
if (root == null) return false;
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while(current.iData != key) // search for node
parent = current;
if(key < current.iData) // go left?
isLeftChild = true;
current = current.leftChild;
else // or go right?
isLeftChild = false;
current = current.rightChild;
if(current == null)
return false; // didn't find it
} // end while
// found node to delete
// if no children, simply delete it
if(current.leftChild==null &&
current.rightChild==null)
if(current == root) // if root,
root = null; // tree is empty
else if(isLeftChild)
parent.leftChild = null; // disconnect
else // from parent
parent.rightChild = null;
// if no right child, replace with left subtree
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;
// if no left child, replace with right subtree
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.rightChild;
else // two children, so replace with inorder successor
// get successor of node to delete (current)
Node successor = getSuccessor(current);
// connect parent of current to successor instead
if(current == root)
root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;
// connect successor to current's left child
successor.leftChild = current.leftChild;
// successor.rightChild = current.rightChild; done in getSucessor
} // end else two children
return true;
} // end delete()
// returns node with next-highest value after delNode
// goes to right child, then right child's left descendents
private Node getSuccessor(Node delNode)
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; // go to right child
while(current != null) // until no more
{ // left children,
successorParent = successor;
successor = current;
current = current.leftChild; // go to left child
// if successor not
if(successor != delNode.rightChild) // right child,
{ // make connections
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
return successor;
public void traverse(int traverseType)
switch(traverseType)
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
System.out.println();
private void preOrder(Node localRoot)
if(localRoot != null)
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
private void inOrder(Node localRoot)
if(localRoot != null)
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
private void postOrder(Node localRoot)
if(localRoot != null)
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
public void displayTree()
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
while(isRowEmpty==false)
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
Node temp = (Node)globalStack.pop();
if(temp != null)
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
else
System.out.print("--");
localStack.push(null);
localStack.push(null);
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
} // end displayTree()
} // end class Tree
class TreeApp
public static void main(String[] args) throws IOException
int value;
double val1;
String Line,Term;
BufferedReader input;
input = new BufferedReader (new FileReader ("one.txt"));
Tree theTree = new Tree();
val1=0.1;
while ((Line = input.readLine()) != null)
Term=Line;
//val1=Integer.parseInt{Term};
val1=val1+1;
//theTree.insert(Line, val1+0.1);
val1++;
System.out.println(Line);
System.out.println(val1);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
while(true)
putText("Enter first letter of ");
putText("show, insert, find, delete, or traverse: ");
int choice = getChar();
switch(choice)
case 's':
theTree.displayTree();
break;
case 'i':
putText("Enter value to insert: ");
value = getInt();
theTree.insert(value, value + 0.9);
break;
case 'f':
putText("Enter value to find: ");
value = getInt();
Node found = theTree.find(value);
if(found != null)
putText("Found: ");
found.displayNode();
putText("\n");
else
putText("Could not find " + value + '\n');
break;
case 'd':
putText("Enter value to delete: ");
value = getInt();
boolean didDelete = theTree.delete(value);
if(didDelete)
putText("Deleted " + value + '\n');
else
putText("Could not delete " + value + '\n');
break;
case 't':
putText("Enter type 1, 2 or 3: ");
value = getInt();
theTree.traverse(value);
break;
default:
putText("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static void putText(String s)
System.out.print(s);
System.out.flush();
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class TreeAppString str = "Hello";
int index = 0, len = 0;
len = str.length();
while(index < len) {
System.out.println(str.charAt(index));
index++;
} -
A Binary Tree Implementation in ABAP
Hi,
Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
Thanks,
Manjula.Hi manjula,
This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It.
It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing through the tree.
For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
*& Report YBINTREE - Build/Print Binary Tree of numbers *
report ybintree .
types: begin of stree,
value type i,
left type ref to data,
right type ref to data,
end of stree.
data: tree type stree.
data: int type i.
data: begin of rnd occurs 0,
num type i,
end of rnd.
start-of-selection.
do 100 times.
generate random number between 0 and 100
call function 'RANDOM_I4'
exporting
rnd_min = 0
rnd_max = 100
importing
rnd_value = int.
store numbers
rnd-num = int.
append rnd.
build binary tree of random numbers
perform add_value using tree int.
enddo.
stored numbers are sorted for comparison
sort rnd by num.
print sorted random numbers
write: / 'Sorted Numbers'.
write: / '=============='.
skip.
loop at rnd.
write: rnd-num.
endloop.
skip.
print binary tree. This should give the same result
as the one listed from the internal table
write: / 'Binary Tree List'.
write: / '================'.
skip.
perform print_value using tree.
skip.
*& Form add_value
text - Build tree with value provided
-->TREE text
-->VAL text
form add_value using tree type stree val type i.
field-symbols: <ltree> type any.
data: work type stree.
if tree is initial. "When node has no values
tree-value = val. " assign value
clear: tree-left, tree-right.
create data tree-left type stree. "Create an empty node for left
create data tree-right type stree. "create an empty node for right
else.
if val le tree-value. "if number is less than or equal
assign tree-left->* to <ltree>. "assign the left node to fs
call add_value recursively with left node
perform add_value using <ltree> val.
else. "if number is greater
assign tree-right->* to <ltree>. "assign the right node to fs
call add_value recursively with right node
perform add_value using <ltree> val.
endif.
endif.
endform. "add_value
*& Form print_value
text - traverse tree from left-mid-right order
automatically this will be sorted list
-->TREE text
form print_value using tree type stree.
field-symbols: <ltree> type any.
if tree is initial. "node is empty
else. "non-empty node
assign tree-left->* to <ltree>. "left node
perform print_value using <ltree>. "print left
write: tree-value. "print the current value
assign tree-right->* to <ltree>. "right node
perform print_value using <ltree>. "print right
endif.
endform. "print_value
pls reward if helps,
regards. -
Having trouble finding the height of a Binary Tree
Hi, I have an ADT class called DigitalTree that uses Nodes to form a binary tree; each subtree only has two children at most. Each node has a "key" that is just a long value and is placed in the correct position on the tree determined by its binary values. For the height, I'm having trouble getting an accurate height. With the data I'm using, I should get a height of 5 (I use an array of 9 values/nodes, in a form that creates a longest path of 5. The data I use is int[] ar = {75, 37, 13, 70, 75, 90, 15, 13, 2, 58, 24} ). Here is my code for the whole tree. If someone could provide some tips or clues to help me obtain the right height value, or if you see anything wrong with my code, it would be greatly aprpeciated. Thanks!
public class DigitalTree<E> implements Copyable
private Node root;
private int size;
public DigitalTree()
root = null;
size = 0;
public boolean add(long k)
if(!contains(k))
if(this.size == 0)
root = new Node(k);
size++;
System.out.println(size + " " + k);
else
String bits = Long.toBinaryString(k);
//System.out.println(bits);
return add(k, bits, bits.length(), root);
return true;
else
return false;
private boolean add(long k, String bits, int index, Node parent)
int lsb;
try
lsb = Integer.parseInt(bits.substring(index, index - 1));
catch(StringIndexOutOfBoundsException e)
lsb = 0;
if(lsb == 0)
if(parent.left == null)
parent.left = new Node(k);
size++;
//System.out.println(size + " " + k);
return true;
else
return add(k, bits, index-1, parent.left);
else
if(parent.right == null)
parent.right = new Node(k);
size++;
//System.out.println(size + " " + k);
return true;
else
return add(k, bits, index-1, parent.right);
public int height()
int leftHeight = 0, rightHeight = 0;
return getHeight(root, leftHeight, rightHeight);
private int getHeight(Node currentNode, int leftHeight, int rightHeight)
if(currentNode == null)
return 0;
//else
// return 1 + Math.max(getHeight(currentNode.right), getHeight(currentNode.left));
if(currentNode.left == null)
leftHeight = 0;
else
leftHeight = getHeight(currentNode.left, leftHeight, rightHeight);
if(currentNode.right == null)
return 1 + leftHeight;
return 1 + Math.max(leftHeight, getHeight(currentNode.right, leftHeight, rightHeight));
public int size()
return size;
public boolean contains(long k)
String bits = Long.toBinaryString(k);
return contains(k, root, bits, bits.length());
private boolean contains(long k, Node currentNode, String bits, int index)
int lsb;
try
lsb = Integer.parseInt(bits.substring(index, index - 1));
catch(StringIndexOutOfBoundsException e)
lsb = 0;
if(currentNode == null)
return false;
else if(currentNode.key == k)
return true;
else
if(lsb == 0)
return contains(k, currentNode.left, bits, index-1);
else
return contains(k, currentNode.right, bits, index-1);
public Node locate(long k)
if(contains(k))
String bits = Long.toBinaryString(k);
return locate(k, root, bits, bits.length());
else
return null;
private Node locate(long k, Node currentNode, String bits, int index)
int lsb;
try
lsb = Integer.parseInt(bits.substring(index, index - 1));
catch(StringIndexOutOfBoundsException e)
lsb = 0;
if(currentNode.key == k)
return currentNode;
else
if(lsb == 0)
return locate(k, currentNode.left, bits, index-1);
else
return locate(k, currentNode.right, bits, index-1);
public Object clone()
DigitalTree<E> treeClone = null;
try
treeClone = (DigitalTree<E>)super.clone();
catch(CloneNotSupportedException e)
throw new Error(e.toString());
cloneNodes(treeClone, root, treeClone.root);
return treeClone;
private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
if(treeClone.size == 0)
cloneNode = null;
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
else if(currentNode != null)
cloneNode = currentNode;
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
public void printTree()
System.out.println("Tree");
private class Node<E>
private long key;
private E data;
private Node left;
private Node right;
public Node(long k)
key = k;
data = null;
left = null;
right = null;
public Node(long k, E d)
key = k;
data = d;
left = null;
right = null;
public String toString()
return "" + key;
}You were on the right track with the part you commented out; first define a few things:
1) the height of an empty tree is nul (0);
2) the height of a tree is one more than the maximum of the heights of the left and right sub-trees.
This translates to Java as a recursive function like this:
int getHeight(Node node) {
if (node == null) // definition #1
return 0;
else // definition #2
return 1+Math.max(getHeight(node.left), getHeight(node.right));
}kind regards,
Jos
Maybe you are looking for
-
Select Options to RFC function modules
Hi all When we use a PERFORM in main program, we can simply use the select-options as for ex., in so_matnr in so_bsart like that without passing any parameters. This way it will take all values given in 'Single values' in the multiple selection optio
-
Ipod touch doesn't sync on Win 7 64 Bit
Hi all, this is my first post, sorry for my english. I have a big problem with the syncronizaztion with my ipod touch 32g 2gen firmware 3.1.2 and ITunes 9.0.2 When I put it into my usb port I encoured on several errors (error 0xE8000065, the ipod can
-
Broadcast/SD Titles and Text: Workflow
I'm curious what, when doing Broadcast Titles and Text, is your workflow. Do you exclusively make slates in Illustrator etc.? Do they look significantly better and function better for Broadcast product than making same in LIveType or Motion. Is there
-
I want to validate PO creation if creation is based on without PR,only for some Material Type.How can we do that.Can any help me out by giving step by Step process. But I want to implement this processs only for some Material Type eg:Raw Material ,Pa
-
Reference a project in a different workspace?
Is it possible to reference a project in a different workspace (aka application)? Or are you restricted only to the projects in the same workspace?