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.
Similar Messages
-
Non-recursive postorder traversal (bst)
Hello!
I'm having difficulty writing a non-recursive postorder traversal for a binary search tree. Not getting an error via compiler but I know that the answer is incorrect. Please provide some insight on what I'm doing wrong!
Here's an example of what I mean by incorrect..
correct postorder answer (done recursively) --> 0 4 2 6 10 12 14 8 18 16
what I'm getting using the function below --> 8 6 2 0 4 14 12 10 18 18
And here's what I have:
public void nonRecursivePostorder(BinarySearchTreeNode<T> root, StringBuffer result)
LinkedStack<BinarySearchTreeNode<T>> stack = new LinkedStack<BinarySearchTreeNode<T>>();
BinarySearchTreeNode<T> currentNode = root;
boolean done;
done = (currentNode == null);
while (!done)
if (currentNode.getLeft() != null)
if (currentNode.getRight() != null)
stack.push(currentNode.getRight());
currentNode = currentNode.getLeft();
else if (currentNode.getRight() != null)
currentNode = currentNode.getRight();
else if (stack.empty())
done = true;
else
currentNode = stack.top();
stack.pop();
System.out.print(currentNode.getData() + " ");
}When you post code, wrap it in code tags.
Anyway, ultimately the solution is to put in debugging tags to see where things are going wrong.
You don't really need that done variable. Just check the stack.
Though actually IIRC, you'd actually need a queue. -
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. -
Hi
I've written the following code for converting Postfix to Infix,it reads a string then reads it letter by letter ,a stack and a Tree is used,and I want to traverse the last object that has poped from the stack,in the following code I used this line:
System.out.println((Character)(((TreeNode)stack.pop()).data));
but it only prints the root of the tree,I tried to traverse it but I don't have any idea,I did sth like this( for traversing another node):
(TreeNode)stack.pop() = ( (TreeNode)stack.pop() ).data;
System.out.println((Character)(((TreeNode)stack.pop()).data));
but it didn't work.
would you plz help me with it.
Here is the code:
import java.util.Scanner;
public class Test
public static void main( String args[])
Scanner input = new Scanner( System.in );
System.out.printf("Enter your String(in Postfix):\n");
String c = input.nextLine();//read a line of text
Stack stack = new Stack();
int i = 0 ;
while( i < c.length() )
char a = c.charAt( i );
if( Character.isLetterOrDigit (a) )
System.out.printf("\n%c" , a );
stack.push( new TreeNode( a ) );
else if( a == '+' || a == '-' || a == '*' || a == '/' )
TreeNode t = new TreeNode( a );
t.insert( 0 , stack.pop() );
t.insert( 1 , stack.pop() );
stack.push( t );
i++;
(TreeNode)stack.pop() = ( (TreeNode)stack.pop() ).data; //<-----Here is the problem
System.out.println((Character)(((TreeNode)stack.pop()).data));
Thax
BitaWell, two things. First, you're trying to assign to a method call, which isn't valid. The compiler probably told you this.
Second, you're popping things from the stack more often than you need to (e.g., for printing) so the stack probably won't be in the state you need.
When you post code, please wrap it in code tags so it'll be legible. Highlight it and then click the CODE button above the text input box. -
N-ary Trees non-recursive traversal algorithms
Hi,
Non-recursive traversals are needed when you are unsure how big the tree's will be. So far all the algorithms I have seen either use their own internal stack
or threading to climb back up the tree.
Here's my attempt that seems to work but I would value so critical evaluation
* An extension of the CommonAST that records the line and column
* number. The idea was taken from <a target="_top"
* href="http://www.jguru.com/jguru/faq/view.jsp?EID=62654">Java Guru
* FAQ: How can I include line numbers in automatically generated
* ASTs?</a>.
* @author Oliver Burn
* @author lkuehne
* @version 1.0
* @see <a target="_top" href="http://www.antlr.org/">ANTLR Website</a>
public class DetailAST
public AST getFirstChild()
public AST getNextSibling()
public int getChildCount()
public DetailAST getParent()
public int getChildCount(int aType)
public String getText()
}This was cut back just to give you enough info
public static AST getLeftMostChild(DetailAST ast) {
DetailAST tempAst = ast.getFirstChild();
while (tempAst.getFirstChild() != null) {
tempAst = tempAst.getFirstChild();
return tempAst;
public static void traverseASTInOrder(DetailAST root) {
DetailAST current = getLeftMostChild(ast);
processNode(current);
while (current != root) {
if (current == current.getParent().getFirstChild()) {
processNode(current.getParent());
if (current.getNextSibling() != null) {
DetailAST sibling = current.getNextSibling();
if (sibling.getChildCount() != 0) {
current = (DetailAST) getLeftMostChild(sibling);
processNode(current);
} else {
current = sibling;
processNode(current);
} else {
current = current.getParent();
// do stuff at inorder traversal
public static void processNode(AST current) {
System.out.println(current.getText());
}for pre-order and post-order John Cowan put forward this algorithm
http://lists.xml.org/archives/xml-dev/199811/msg00050.html
traverse(Node node) {
Node currentNode = node;
while (currentNode != null) {
visit(currentNode); //pre order
// Move down to first child
Node nextNode = currentNode.getFirstChild();
if (nextNode != null) {
currentNode = nextNode;
continue;
// No child nodes, so walk tree
while (currentNode != null) {
revisit(currentNode) // post order
// Move to sibling if possible.
nextNode = currentNode.getNextSibling();
if (nextNode != null) {
currentNode = nextNode;
break;
// Move up
if (currentNode = node)
currentNode = null;
else
currentNode = currentNode.getParentNode();
}Any comments, criticisms or suggestions ?
regards
David ScurrahStack is recursion? As far as I know recursion is when
function (method) calls itself. Just using some
Collection, which java.util.Stack implements is not
recursion.
Regards
PawelStacks are used to implement recursive algorithms. What happens in most languages when you make a function call? Each function has an "activation record" where it stores its local variables and parameters. This activation record is usually allocated on a stack. Thus for any recursive algorithm, there is a non-recursive algorithm that uses a stack.
In the OP's case you don't need a stack because of the peculiarities of tree traversal when you have a pointer to the parent node. (Namely, no cycles and you can get back to where you've been) So the algorithms he gave should work fine.
My only "criticism" would be that it may be more useful to implement these algorithms with the iterator pattern. So you would have a tree with some functions like:
public class Tree{
public TreeIterator inOrderIteraror();
public TreeIterator preOrderIterator();
}Where the TreeIterator would look like a java.util.Iterator, except maybe you want some additional utility methods in there or something.
Other than that, non-recursive algorithms are defnitely the way to go. -
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 -
Hi guys i am used in creating binary trees ,tell me how do we create non binary trees in java.
public class Node {
private final Object payload;
private final Set<Node> children;
public Node(Object payload) {
this.payload = payload;
children = new HashSet<Node>();
// now add methods to add/remove children, a method to do something with the payload (say,
// a protected method that passes the payload to a method specified by some kind of interface),
// and methods to recurse over children.
}Actually rather than using Object probably should have generic-ized the class, but whatever. -
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 -
How to Recursively traverse a Dom Tree
Hi there, I'm new to java and xml and would like to see some sample code on recursively traversing a DOM tree in java, printing out all Element, Text, etc to the console window.
Please helpUse this: DomRead.java at your own risk. caveat: this gets screwed up if the attributes are multi-valued. You can use XPath to get around that. I am struggling with the proper XPath expressions.
import org.xml.sax.*;
import org.w3c.dom.*;
import java.util.*;
* version 1.0
public class DomRead implements ErrorHandler
private static final String CRLF = System.getProperty("line.separator");
private static String key = "";
private static String value = "";
private Hashtable elements = new Hashtable();
* This constructor has to be used to pass in the DOM document which needs to
* be read so that this class can generate the hashtable with the attributes as
* keys and their corresponding values.
public DomRead(Document rootDoc)
process(rootDoc);
private void processChild(NodeList root)
for(int i=0;i<root.getLength(); i++)
process(root.item(i));
private void printAttrib(Node root)
NamedNodeMap attrib = root.getAttributes();
int len = attrib.getLength();
if(len == 0) return;
for(int i=0; i < len ; i++)
Attr attribute = (Attr) attrib.item(i);
key = attribute.getNodeValue();
private void process(Node root)
switch( root.getNodeType())
case Node.DOCUMENT_NODE :
Document doc = (Document) root;
processChild(doc.getChildNodes());
break;
case Node.ELEMENT_NODE :
root.setNodeValue(root.getNodeValue() );
printAttrib(root);
processChild(root.getChildNodes());
break;
case Node.TEXT_NODE :
Text text = (Text) root;
value = text.getNodeValue().trim();
//Log("Value: "+value+CRLF);
if(!value.equalsIgnoreCase(""))
elements.put(key, value);
break;
* Use this method, if you intend to print out the contents of the generated
* hashtable.
public void printElements()
for (Enumeration enum = elements.keys(); enum.hasMoreElements() ;)
String tKey = (String)enum.nextElement();
Log(tKey+"::::"+(String)elements.get(tKey));
* This method returns the Hashtable with the attributes that have non-empty
* values.
public Hashtable getElements()
return elements;
public void error(SAXParseException e)
e.printStackTrace();
public void warning(SAXParseException e)
e.toString();
public void fatalError(SAXParseException e)
e.printStackTrace();
private static void Log(String log)
System.out.print(log+CRLF);
} -
Creating non binary trees in Java
Hi everybody actually i am used in creating binary trees in java,can u please tell me how do we create non binary -trees in java.
Hi,
Can u let us know the application area for Non binary tree.
S Rudra -
Recursive version of preorder traversal???
Can some one please give me a sample code of what recursive version of preorder traversal should look like???
thank you :)JavaLearner2009 wrote:
Can some one please give me a sample code of what recursive version of preorder traversal should look like???Could you please do your own homework?
Could you please limit the amount of punctuation characters to one at each appropriate location?
Could you please learn [How To Ask Questions The Smart Way|http://www.catb.org/~esr/faqs/smart-questions.html]?
Could you please ask a specific question about a concrete problem that you find while doing your own homework?
thank you :)thank you :) -
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. -
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!
Maybe you are looking for
-
Upgraded to yosemite now no email images. Anyone know how to fix?
I upgraded to Yosemite 2 days ago and now my emails come in without images. How do I fix it?
-
I need the sap bw table names for ROLE's
I need the sap bw table names for ROLE's . thanks
-
In Facebook mobile when you scroll through friends lists now every third swipe to scroll down doesn't respond. Extremely annoying.
-
Is there a way to get my iTunes library on a galaxy s4?
i upgrade my phone in 2 weeks and i was thinking on upgrading to a galaxy s4. i currently have an ipnone 4s and i dont think it is worth upgrading to an iphone 5 because its basicaly the same thing. i havent bought that many apps so that doesnt wor
-
Itunes is saying that it can not find software update to restore my iphone 5c.
Can someone please help me figure out how to get my phone back to wroking i have tried to turn it off then on but it wouldnt let me do a full shut down and when i plugged it in to my computer itunes said it can not find software update for iphone. I