Binary tree inorder traversal without recursion
Using Java, write a method that does an in-order traversal of a binary tree WITHOUT using recursion. based on the following code
BTreeNode.java
public class BTreeNode
public BTreeNode LEFT;
public BTreeNode RIGHT;
public String VALUE;
BTreeUtil.java
public class BTreeUtil
public static void listNodes(BTreeNode a_oRootNode)
// insert code here...
}
This is definitely the wrong place to post this. Nevertheless you'll have to use a stack. While traversing down the tree you push the parents onto the stack.
stephan
Similar Messages
-
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 -
Non recursive preorder traversal of binary tree
hi,
I am trying to implement a non-recursive traversal of binary tree. I already know the recursive one.
I am trying to do it by using a Stack.
I begin by Pushing the root of an element on to a stack, and then run a while loop in which i pop an element of the stack and get its children from right to left. and push it in the same order on to the stack. So during the next iteration of my while loop the top most element gets popped and its children and pushed on to the stack in the above manner.
but when i pop an element from a stack its popped as an object so i dont know how to access its children.
help me i am really stuck.Hi, I suppose you have something like this :
class Stack {
public void push( Object object ) throws ... { ... }
public Object pop() throws ... { ... }
class Element {
Element elem;
stack.push(elem);
/* because pop() method return an object of type Object
** if you are sure that your stack only contains Element object
** then you need to cast (change the type of) what the pop() method
** returns in this way :
elem = (Element)stack.pop();
...further reading on casting will be a good idea anyway. -
How to remember the path while traverse a binary tree?
Hi, again, I have difficulty handling tree search problems.
The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
I think the signature should be:
// The path contains only 0s and 1s. 0 means go left and 1 means go right.
public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
// the class Node only has two fields:
Node{
Node left;
Node right;
I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
Anyone wants to help?Hi, JosAh,
That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
So I changed your code to be:
Stack search(Node root, Node node, Stack<Integer> path) {
if (root == null || root.right ==right) return null;
if (root.equals(node)) return path;
path.push(0);
if (search(root.left, node, path) != null) return path;
path.pop();
path.push(1);
return search(root.right, node, path);
}I simply tested it with
Stack<Integer> path = new Stack<Integer>();
System.out.println( root, root.right.right, path);
root is the root of a complete binary tree with 7 nodes(4 leaves).
Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
Considerring , the right branch never pops, I changed it into
Then I changed it to :
Stack search(Node root, Node node, Stack<Integer> path) {
if (root == null || root.right ==right ) return null;
if (root.equals(node)) return path;
path.push(0);
if (search(root.left, node, path) != null) return path;
path.pop();
path.push(1);
if (search(root.right, node, path) != null) return path;
path.pop();
return path;
With the same test case, it returns [].
I will keep working on it.
Cheers,
Message was edited by:
since81
Message was edited by:
since81 -
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 Pretty Print a Binary Tree?
I'm trying to display a Binary Tree in such a way:
________26
___13_________2
1_______4 3_________1
(without the underscores)
however I cannot figure out the display method.
class BinaryNode
//Constructors
BinaryNode leftChild, rightChild;
Object data;
BinaryNode()
leftChild = null;
data = null;
rightChild = null;
BinaryNode( Object d, BinaryNode left, BinaryNode right)
leftChild = left;
data = d;
rightChild = right;
//Height
public static int Height(BinaryNode root)
if (root == null)
return 0;
if ((Height(root.leftChild)) > Height(root.rightChild))
return 1 + Height(root.leftChild);
return 1 + Height(root.rightChild);
//Count
public static int Count(BinaryNode root)
if(root==null)
return 0;
return 1 + Count(root.leftChild) + Count(root.rightChild);
//Display
public static void Display(BinaryNode root)
int level = 2^(Level(root)-1)
for (int i = 1; i<Height(root)+1; i++)
System.out.printf("%-4s%
Display(root, i);
System.out.println();
public static void Display(BinaryNode root, int level)
if (root!=null)
if(level==1)
System.out.print(root.data + " ");
else
Display(root.leftChild, level-1);
Display(root.rightChild, level-1);
//Level
public static int Level(BinaryNode root)
if(root==null)
return 0;
if(root.leftChild == null && root.rightChild == null)
return 1;
return Level(root.leftChild) + Level(root.rightChild);
Edited by: 815035 on Nov 23, 2010 12:27 PMThe example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
Unfortunately it is also quite difficult to accomplish using System.out.print statements.
You have to print out the root of the tree first (its at the top)
However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
So you will need to traverse the tree at least twice.
Once to work out the offsets, and again to print out the values.
The working out of offsets would have to be a depth search traversal I think
The printing of the values in this fashion would be a breadth first traversal.
I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
ie the root was on the left, the leaves of the tree on the right of the screen.
That meant you could do an inorder depth traversal of the tree to just print it once.
hope this helps,
evnafets -
So this is my first post here and i am beginning to like this forum.
Can anybody help me on how to construct Binary tree from inorder and postorder traversals,i just want to know the algorithm so that i can apply it.
Please help.I would like to pick a minor little nit with this analysis. The algorithm that has been proposed assumes that all the nodes are all distinct and that having selected the root from the end of the post-order listing that it is POSSIBLE to find it in the in-order list. What if you find multiple copies of this node?
If multiple copies of the root are found, you must have a method to distinguish, which one is the proper dividing point. In the worst possible case, the problem can not be solved at all. For example suppose my post-order and my in-order lists were these:
a a a a a
a a a a a
The shape of the tree is indeterminant in this case.
If you allow different tree nodes to contain identical values your recursive algorithm needs some modification.
The fix is this:
1) allow your recursive algorithm to fail (and report back any success or failure)
This can and happen if the two lists that you passed in are incompatible. For example they could have different nodes in them.
2) when you pick the root off the end of the post order list, you search for it in the in-order list, you could find multiple matches or you could find no matches. You must explore each of these independently because each one could lead to a possible different solution, or could lead to no solution. Of course in the case of no matches, you must report back a failure.
Depending on your needs, you can either stop the first time that you have successfully assembled a tree that matches the two supplied inputs, or you can have it grind on and have it enumerate all the possible tree arrangements that could have generated from the two traversals that you started with.
It might help to visualize if you write out all the possible trees with just the three nodes AAB. There are 15 of them, 5 with B at the root, 5 with A at the root and B in the left and 5 with B in the right. It is easy to draw the trees and to immediately write both their in-order and their post-order traversals.
Any traversal is just a list of the 3 nodes and there are 3 arrangements, AAB, ABA, and BAA. There are exactly 9 ordered pairs of these traversals so you can't get all 15 trees from the 9 pairs.
Sho nuff, three ordered pairs are unambiguous and generate a single unique tree(e.g. in:BAA post:ABA) and six of them come from ambiguous pairs of trees (e.g. in:ABA post:ABA - you can't tell if this is a tree ABA all leaning to the left or all leaning to the right)
Enjoy -
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. -
Ok people I need help!
I want to create, from a pre-order and in-order sequences, the post-order sequence! Obviously there are no repeated elements (characters from A to Z at this case).
The tree root it's the first character from pre-order and after that it's easy to take left and right sequences.
I found an interesting explanation: http://www.dcs.kcl.ac.uk/staff/pinz...st/html/l7.html
I've tried everything to make it recursive I think that's the best way to do it but somehow I can't make it work! My last code:
import java.io.*;
import java.util.*;
public class Problem
static String readLn (int maxLg) // utility function to read from stdin
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
try
while (lg < maxLg)
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
catch (IOException e)
return (null);
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
public static void main (String []args)
for (int set = Integer.parseInt(readLn(10).trim()); set != 0; set--)
StringTokenizer tok = new StringTokenizer(readLn(100).trim()," ");
String preOrd = tok.nextToken();
String inOrd = tok.nextToken();
char root = preOrd.charAt(0);
BinaryNode tree = new BinaryNode(root);
// Left and right from inOrd
tok = new StringTokenizer(inOrd,Character.toString(root));
String inOrdLeft = tok.nextToken();
String inOrdRight = tok.nextToken();
// Take left and right from preOrd
String preOrdLeft = preOrd.substring(1,inOrdLeft.length()+1);
String preOrdRight = preOrd.substring(inOrdLeft.length()+1);
tree.left = work (preOrdLeft, 0, inOrdLeft);
tree.right = work (preOrdRight, 0, inOrdRight);
tree.printPostOrder();
System.out.println();
public static BinaryNode work (String preOrd, int preOrdPoint, String inOrd)
char nodeChr = preOrd.charAt(preOrdPoint);
String nodeStr = Character.toString(nodeChr);
//System.out.println("Root: "+nodeStr+" preOrd: "+preOrd+" inOrd: "+inOrd);
BinaryNode tempTree = new BinaryNode(nodeChr);
StringTokenizer tok = new StringTokenizer(inOrd,nodeStr);
try
String newInOrdLeft = tok.nextToken();
if (newInOrdLeft.length() == 1) { tempTree.left = new BinaryNode(newInOrdLeft.toCharArray()[0]); }
else if (newInOrdLeft.length() != 0) { tempTree.left = work(preOrd, preOrdPoint+1, newInOrdLeft); }
catch (NoSuchElementException e) {}
try
String newInOrdRight = tok.nextToken();
if (newInOrdRight.length() == 1) { tempTree.right = new BinaryNode(newInOrdRight.toCharArray()[0]); }
else if (newInOrdRight.length() != 0) { tempTree.right = work(preOrd, preOrdPoint+1, newInOrdRight); }
catch (NoSuchElementException e) {}
return tempTree;
class BinaryNode
char chr;
BinaryNode left = null;
BinaryNode right = null;
BinaryNode()
BinaryNode(char c)
this(c, null, null);
BinaryNode(char c, BinaryNode lt, BinaryNode rt)
chr = c;
left = lt;
right = rt;
static int size(BinaryNode t)
if (t == null) { return 0; }
else { return size(t.left) + 1 + size(t.right); }
static int height(BinaryNode t)
if (t == null) { return 0; }
else { return 1 + Math.max(BinaryNode.height(t.left), BinaryNode.height(t.right)); }
void printPostOrder () {
if( left != null )
left.printPostOrder( ); // Left
if( right != null )
right.printPostOrder( ); // Right
System.out.print(chr); // Node
static BinaryNode insert (char c, BinaryNode t)
Character tmp = new Character(c);
if (t == null)
t = new BinaryNode(c, null, null);
else if (tmp.compareTo(new Character(t.chr)) < 0)
t.left = insert(c, t.left );
else if (tmp.compareTo(new Character(t.chr)) > 0)
t.right = insert(c, t.right);
return t;
}I don't know if this is a translation of your C code, but it can reconstruct any binary tree (with letters as nodes and no duplicates) from preorder and inorder traversals. Hope it helps.
import java.util.*;
public class ReconstructTree {
public ReconstructTree() {
public static void main(String[] args)
String preorder = "ABDGKLRVWSXCEHMNFIOTUJPYQZ";
String inorder = "KGVRWLSXDBAMHNECTOUIFPYJZQ";
Map table = new HashMap();
Map table2 = new HashMap();
for(int i=0; i<inorder.length(); i++)
table.put("" + inorder.charAt(i), new Integer(i));
table2.put(new Integer(i), "" + inorder.charAt(i));
List temppreorder = new ArrayList();
for(int i=0; i<preorder.length(); i++)
temppreorder.add(table.get("" + preorder.charAt(i)));
Node root = constructTree(temppreorder);
printPostOrder(root, table2);
public static void printPostOrder(Node root, Map table)
if(root == null)
return;
Node left = root.getLeft();
Node right = root.getRight();
printPostOrder(left, table);
printPostOrder(right, table);
System.out.print(table.get(new Integer(Integer.parseInt("" + root.getValue()))));
public static Node constructTree(List preorder)
Iterator it = preorder.iterator();
int r = ((Integer)it.next()).intValue();
Node root = new Node(r);
Node node = root;
while(it.hasNext())
node = root;
int a = ((Integer)it.next()).intValue();
while(true)
r = node.getValue();
if(a < r)
if(node.getLeft() == null)
node.setLeft(new Node(a));
break;
else
node = node.getLeft();
else
if(node.getRight() == null)
node.setRight(new Node(a));
break;
else
node = node.getRight();
return root;
public static class Node
private Node left = null;
private Node right = null;
private int value;
public Node(int v)
value = v;
public int getValue()
return value;
public Node getLeft()
return left;
public Node getRight()
return right;
public void setLeft(Node l)
left = l;
public void setRight(Node r)
right = r;
} -
Hi guys ;
I have a BST class .One of its methods is preorder travesal.
this method traverse theBinary tree in preorder and prints nodes data to a file.
Now what i want to do is to be able to construct the binary tree by reading data from this file : keeping in mind the data nodes were saved to this file in preorder.
Is this a possible thing to do ?
How can I do this ?
Is there a better way to save a binary tree to a file and the other way : read from file and construct the tree again?
Many thanks for helping !I'd like to say thanks too.. it really helped me out!
I used a few minutes (or so ;) to figure out the functions for saving and rebuilding the tree, so I thought I'd post it here, if anyone could use it. Note: this ugly pseudocode might look a little like VB.net-code, which happened completely by accident..
Private Function SearchForLeaves(ByVal StartNode As Node, ByVal BitString As String) As String
'Recursive function. If a leaf is found on left or right side of the branch,
'then print the binary pattern used to get there, else call the function again on the next branch.
Dim SavedTree As String
With StartNode
If .LeftChild.Type = NodeType.Leaf Then
Print .leftChild.Value & " " & Bitstring & "0"
SavedTree += "!" & .LeftChild.Value
Else
SearchForLeaves(.LeftChild, BitString & "0")
End If
If .RightChild.Type = NodeType.Leaf Then
Print .leftChild.Value & " " & Bitstring & "1"
SavedTree += "!" & .RightChild.Value
Else
SearchForLeaves(.RightChild, BitString & "1")
End If
SavedTree += "?"
End With
Return SavedTree
End Function
Private Function RebuildTree(ByVal savedTree As String) As Node
Dim n As Node
While Len(savedTree) > 0
If savedTree.StartsWith("!") Then
CropString(savedTree)
n = New Node(NodeType.Leaf)
n.Value = CropString(savedTree)
Stack.Push(n)
End If
If savedTree.StartsWith("?") Then
CropString(savedTree)
n = New Node(NodeType.Branch)
n.RightChild = Stack.Pop
n.LeftChild = Stack.Pop
n.LeftChild.Parent = n
n.RightChild.Parent = n
Stack.Push(n)
End If
End While
Return Stack.Pop
End Function
Private Function CropString(byRef cropMe as String) As String
Dim L As String
L = cropMe.Substring(0, 1)
cropMe = cropMe.Substring(1)
Return L
End FunctionCropString just crops off and returns the first character of the string.. I'm going to rewrite this whole thing, but right now I'm just pleased I figured out how to make it work :)
Cheers! -
Hello,
The problem I'm having is how to empty a binary tree. Here is my code for MyBinaryTree:
public class MyBinaryTree implements BinaryTree {
private BinaryTreeNode root;
protected static int numNodes;
private static String tree = "";
* Constructor that creates a binary tree with a root.
* @param r The root node
* @param num The number of nodes
public MyBinaryTree(BinaryTreeNode r, int num) {
root = r;
numNodes = num;
* Method to make the binary tree empty.
public void makeEmpty() {
root.left = null;
root.right = null;
root = new BinaryTreeNode(null,null,null,null,null);
numNodes = 0;
* Method to make a root with key k and element el.
* @param k The key of the root
* @param el The element in the root
public void makeRoot(Comparable k, Object el) {
root = new BinaryTreeNode(k,el);
numNodes++;
* Method to return the root of the binary tree.
* @return The root of the tree
public BinaryTreeNode root() {
return root;
* Method to return the left child of a node.
* @param node The node whose left child is wanted.
* @return The left child of the node
* @see NoNodeException
public BinaryTreeNode leftChild(BinaryTreeNode node) throws NoNodeException {
if (node.left == null) throw new NoNodeException("No left child!");
else return node.leftChild();
* Method to set the left child of node "node".
* @param node The node to be given a left child
* @param child The node to be set as left child
public void setLeftChild(BinaryTreeNode node, BinaryTreeNode child) {
node.setLeftChild(child);
numNodes++;
* Method to return the right child of a node.
* @param node The node whose right child is wanted.
* @return The right child of the node
* @see NoNodeException
public BinaryTreeNode rightChild(BinaryTreeNode node) throws NoNodeException{
if (node.right == null) throw new NoNodeException("No right child!");
else return node.rightChild();
* Method to set the right child of node "node".
* @param node The node to be given a right child
* @param child The node to be set as right child
public void setRightChild(BinaryTreeNode node, BinaryTreeNode child) {
node.setRightChild(child);
numNodes++;
* Method to return the parent of a node.
* @param node The node whose parent is wanted.
* @return The parent of the node
* @see NoNodeException
public BinaryTreeNode parent(BinaryTreeNode node) throws NoNodeException {
if (node.p == null) throw new NoNodeException("No parent!");
else return node.parent();
* Method to set the parent of node "node".
* @param node The node to be given a parent
* @param pt The node to be set as parent
public void setparent(BinaryTreeNode node, BinaryTreeNode pt) {
node.setParent(pt);
numNodes++;
* Method to return the key of the specified node.
* @param node The node with the key to be returned
* @return The key of the node
public Comparable getKey(BinaryTreeNode node) {
return node.getKey();
* Method to set the key of the specified node.
* @param node The node for which the key will be set.
* @param k The key to be set.
public void setKey(BinaryTreeNode node, Comparable k) {
node.setKey(k);
* Method to get the element in the specified node.
* @param node The node with the element to be returned.
* @return The element in the node.
public Object getElement(BinaryTreeNode node) {
return node.getElement();
* Method to put an element into the specified node.
* @param node The node that will have an element put in it.
* @param o The element to be inserted.
public void setElement(BinaryTreeNode node, Object o) {
node.setElement(o);
* Method to add a left child to the specified node.
* @param theNode The node that the left child will be added to.
* @param k The key associated with the left child.
* @param el The element in the left child.
public void addLeftChild (BinaryTreeNode theNode, Comparable k, Object el) {
BinaryTreeNode temp = new BinaryTreeNode(k,el);
temp.setParent(theNode);
theNode.setLeftChild(temp);
numNodes++;
* Method to add a right child to the specified node.
* @param theNode The node that the right child will be added to.
* @param k The key associated with the right child.
* @param el The element in the right child.
public void addRightChild (BinaryTreeNode theNode, Comparable k, Object el) {
BinaryTreeNode temp = new BinaryTreeNode(k,el);
temp.setParent(theNode);
theNode.setRightChild(temp);
numNodes++;
* Method to remove the left child of the specified node.
* @param theNode The node which the left child will be removed.
public void removeLeftChild(BinaryTreeNode theNode) {
((BinaryTreeNode)(theNode.left)).p = null;
theNode.left = null;
numNodes--;
* Method to remove the right child of the specified node.
* @param theNode The node which the right child will be removed.
public void removeRightChild(BinaryTreeNode theNode) {
((BinaryTreeNode)(theNode.right)).p = null;
theNode.right = null;
numNodes--;
* Private method to perform an inorder traversal on the tree.
* @param t A MyBinaryTree object
* @param n The starting node.
private static String inorderPrint(MyBinaryTree t, BinaryTreeNode n) {
String spaces = "";
for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
if (n.left != null || n.right != null) inorderPrint(t,t.leftChild(n));
tree += spaces + n.getElement();
if (n.left != null || n.right != null) inorderPrint(t,t.rightChild(n));
return tree;
* Private method to perform an inorder traversal on the tree.
* @param t A MyBinaryTree object
* @param n The starting node.
* @param pos The current position in the tree.
* @return A tree with an asterix beside the current position
private static String inorderPrint2(MyBinaryTree t, BinaryTreeNode n,
BinaryTreeNode pos) {
String spaces = "";
for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
if (n.left != null || n.right != null) inorderPrint2(t,t.leftChild(n),pos);
if (n.getElement() == pos.getElement()) tree += spaces + n.getElement() + "*";
else tree += spaces + n.getElement();
if (n.left != null || n.right != null) inorderPrint2(t,t.rightChild(n),pos);
return tree;
* Method to return a String representation of the binary tree.
* @return String representation of the binary tree
public String toString() {
if (root.getElement() == null) return "*** Tree is empty ***";
else {
MyBinaryTree temp = new MyBinaryTree(root,numNodes);
return inorderPrint(temp,root);
* Method to return a String of the binary tree with an asterix beside the
* current position.
* @param currentPosition The current position.
* @return A String of the tree with an asterix by the current position
public String toString(BinaryTreeNode currentPosition) {
if (root.getElement() == null) return "*** Tree is empty ***";
else {
MyBinaryTree temp = new MyBinaryTree(root,numNodes);
return inorderPrint2(temp,root,currentPosition);
}Those are all the methods I'm allowed to have. When I run makeEmpty, it seems to work, but then if I do makeRoot, the old tree prints again. It's quite bizarre. Any tips on how to empty the tree correctly?Here is the BinaryTreeNode code.
public class BinaryTreeNode {
// Instance variables (Note: they are all "private")
protected Comparable key; // The key at this node
protected Object element; // The data at this node
protected BinaryTreeNode left; // Left child
protected BinaryTreeNode right; // Right child
protected BinaryTreeNode p; // The Parent
// Constructors
BinaryTreeNode( Comparable theKey, Object theElement, BinaryTreeNode lt,
BinaryTreeNode rt, BinaryTreeNode pt ) {
key = theKey;
element = theElement;
left = lt;
right = rt;
p = pt;
BinaryTreeNode( Comparable theKey, Object theElement) {
key = theKey;
element = theElement;
left = null;
right = null;
p = null;
// return the key attached to this node
public Comparable getKey() {
return key;
// set the key attached to this node to be Comparable k
public void setKey(Comparable k) {
key = k;
// return the element attached to this node
public Object getElement() {
return element;
// set the element attached to this node to be Object o
public void setElement(Object o) {
element = o;
// return left child
public BinaryTreeNode leftChild() {
return left;
// set left child to be node n
public void setLeftChild(BinaryTreeNode n) {
left = n;
// return right child
public BinaryTreeNode rightChild() {
return right;
// set right child to be node n
public void setRightChild(BinaryTreeNode n) {
right = n;
// return parent
public BinaryTreeNode parent() {
return p;
// set parent to be node n
public void setParent(BinaryTreeNode n) {
p = n;
} -
Any good algorithm to balanced a strict binary tree for a ordered set
Hi,
I have created a syntax tree of a binary operator that is associative but not commutative. The resultant is a unbalanced strict binary tree.
I have tried using AVL tree as well as a heap. But they will occasionally destruct the non-commutative property of the syntax tree.
Is there any efficient algorithm that I can used to balance this tree?
Thank you.Is linear time good enough?
1. Traverse your tree to build a list.
2. Recursively turn the list into a tree. Pseudocode for this step: fun listToTree( [a] ) = Leaf(a)
| listToTree( xs ) = Node( listToTree(firstHalf(xs)), listToTree(secondHalf(xs)) ); -
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 -
DefaultMutableTreeNode inorder traversal ?
Hi,
I need to traverse a JTree using inorder traverse. any suggestion??? help pls.
Inorder Traverse is visiting all nodes of tree from left to right.Hi.
Inorder traversal will only work with binary trees since you don't know when to process the current node when you've got variating number of children. Let's say you've got a (binary) tree like this:
1
2 3
4 5Then inorder would give you 4, 2, 5, 1, 3 - after the rule: first process the left child, then the root (the current node), then the right child.
But what would it look like in case you've got a tree like that:
1
/|\
2 3 4When would the '1' appear in the output? pre- and postorder will work fine becaue processing the curent node before or after the children is easy - but you don't know the position when to process it when using inorder traversal.
Of course you could count the children and say that the 'middle' is between them - e.g. with five children, the root is to be processed after child #2 or #3 to be in the middle - but that'd be no inorder processing since that doesn't really exist for tree with variable children amounts.
I might be the case that you know that your JTree will always have two or less children for each node - the you just have to process the current node after the first and before the second child. But when using DefaultMutableTreeNode you cannot be sure about this since that class allows any number of children.
HTH, cheers
kelysar
Maybe you are looking for
-
I am using a WD My Passport to try and do a time machine backup for the first time, on my iMac desktop. the first couopleo of times I did it, it was really slow and then crashed after a few mins. I started again as if it was a new external harddrive
-
I just finished dowloading the new osx upadte and my iphoto program dosen't work anymore
i just finished dowloading the new osx upadte and my iphoto program dosen't work anymore
-
Hi guys, i need that the help match code apperas in one select-options parameter. Select-options: PERNR for PA0001-PERNR , the one i need is the same i use in se51 (screen painter), in help search is: EHS00SHLP_PREM i need something like: Select-opti
-
What are default Zend Session handling best practices to prevent Cross Site Request Forgery?
I have enjoyed the David Powers book Adobe Dreamweaver CS5 with PHP: Training from the Source - and have put many of the examples into practice. I have a security related concern that may be tied to the Zend::Auth example in the book. While this i
-
Co-Product partial Qty. processing.
Hi, I have incorporated a Co-Product Scenario here at client end. This is a Injection Mold Processing company, they have a scenario where in there are 2 products being generated with a single PRT on the same machine, i.e. a Co-Product scenario. Prodn