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.

Similar Messages

  • Binary Tree Implementations - why both key and value?

    Hi there!
    I'm sitting here implementing a binary tree, and I was just wondering why most of the binary tree examples encapsulate both a key AND a value in their nodes. Wouldn't it be sufficient to just store comparable objects in the nodes (or provide a comparator for alternative ordering)?
    Thanks again, Oliver
    P.S.:Any suggestions on good books (free E-Books preferred :-)) on ADTs and algorithms? I'm reading 'Data Structures And Algorithms In Java' by Robert Lafore and not very happy with it (the examples are just plain awful).

    Trollhorn wrote:
    Hi there!
    I'm sitting here implementing a binary tree, and I was just wondering why most of the binary tree examples encapsulate both a key AND a value in their nodes. Wouldn't it be sufficient to just store comparable objects in the nodes (or provide a comparator for alternative ordering)?Yes.
    Thanks again, Oliver
    P.S.:Any suggestions on good books (free E-Books preferred :-)) on ADTs and algorithms? I'm reading 'Data Structures And Algorithms In Java' by Robert Lafore and not very happy with it (the examples are just plain awful).As online resources:
    [http://www.cs.princeton.edu/introcs/44st/]
    [http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-006Spring-2008/CourseHome/index.htm]
    I don't know of any eBooks on the subject, but I can recommend an excellent hard copy book:
    Introduction To Algorithms, by Cormen et al. [http://highered.mcgraw-hill.com/sites/0070131511/information_center_view0/]

  • Binary Tree Implementation

    Hi,
    How to implement Binary search tree in java?
    How to create node & how to do backtracking?
    Thanks & Regards,
    Sathyavathy S

    Pretty much like in most other OO languages.
    What exactly is your problem? Do you have a bug in your code, a compiler error or don't you understand how a binary tree works?

  • 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

  • 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

  • Searching for a certain  binary tree from another tree........

    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:
    since81

    I'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 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
    }

  • Binary trees in Java

    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 advance

    Lulu 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 for parsing algebraic expressions

    hi all
    i have a project to do.. i need to read in an algebraic expression, parse it and form a binary tree. later use that tree to evaluate the expressions when the actual value for those variables are passed..
    can anyone tell me how to go about doing this.
    im a beginner in java..
    tks

    first of, your going to need three stacks. The implementation of a stack in JAVA is something that's easy to find, do a forum search. Your going to need a Binary Node as well. One stack will hold the operator elements of your algebraic expression, another will hold the numeric values, and the final will hold your binary nodes:
    expression: 4 + 6 - (6 * 9)
    now there are some rules that should be followed. Whenever a closing parenthesis is encountered ")", pop an operator, pop two numbers, and create the corresponding binary node.
    order of operations:
    push 4 onto numberStack
    push + onto operatorStack
    push 6 onto numberStack
    push - onto operatorStack
    push ( onto operator Stack
    push 6 onto numberStack
    push * onto operatorStack
    push 9 onto numberStack
    ")" encountered
    Now, your stacks look something like this:
    operatorStack: [ +, -, (, *, ) ]
    numberStack: [ 4, 6, 6, 9 ]
    pop 9 and 6 from numberStack, pop * from operatorStack
    build a binaryNode using these three elements
    push this node onto the binaryNodeStack
    I.E. using the expression above:
    / \ is the resulting binary node once the ")" is received.
    6 9
    etc.. there are some rules regarding when to pop and build binary nodes, it's been a while since i did this assignment and frankly my brain hurts, hope this gets you started, good luck.

  • How to make a binary tree

    i have this assignment for school. The first thing it says is: Write a binary tree class named my_Tree as the basic data structure. What does this mean? Can anyone give me an example of the java code that this should be written in?
    Also, i have to sort a sequence of numbers in increasing order. I have the command line prompt written already, but how do i sort it using if/else statements? Thanks a lot. I'm really bad at java programming.

    i dont really understand that? Im really slow at
    this. Can you clarify?Sorry. Here is a more complete implementation of a node.
    // header file for class Node
    // copywrong filestream. no rights reserved
    #ifndef _NODE_H_
    #define _NODE_H_
    class Node
       public:
          Node();
          Node(int x);
          Type getinfo();
          Node *getleft();
          Node *getright();
          void setinfo(Type x);
          void setleft(Node *n);
          void setright(Node *n);
       private:
          int info;
          Node *left;
          Node *right;
    #endif

  • Emptying a Binary Tree

    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;
    }

  • Drawing a binary tree

    Hi guys ;
    I'm trying to write a Java GUI that draws a binary tree on a JPanel.
    the tree is dynamically filled while user is inserting nodes.
    I need a quit robust Implementation so that the tree is properly drawn with lines connecting nodes and most IMPORTANT ; the panel can expend to fit the tree (dynamically).
    can any one tell me how to get started ?
    Many thanks !

    My advice is to use a graphics framework, e.g. look at Piccolo:
    http://www.cs.umd.edu/hcil/piccolo/index.shtml
    If you put your panel in a piccolo scrollpane it will be able to expand in all directions, something that is very hard to achieve otherwise.
    OTOH Piccolo is not a dedicated graph framework (which knows about the distinction of nodes and edges and how to connect them). It comes with an example, though how to implement that.
    There are more dedicated graph frameworks, e.g. JGraph:
    http://sourceforge.net/projects/jgraph/

  • Like to see few real life usage of Binary Tree C#

    whenever we read something about BTree then this kind of program shown in article with code.
    code as follows.
    Main File
    static void Main(string[] args)
    //Creating the Nodes for the Tree
    Node<int> tree = new Node<int>('6');
    tree.Left = new Node<int>('2');
    tree.Right = new Node<int>('5');
    Console.WriteLine("Binary Tree Display");
    Console.WriteLine(tree.Data);
    Console.ReadLine();
    Node Class
    class Node<T> where T : IComparable
    private T data;
    public Node<T> Left, Right;
    public Node(T item)
    data = item;
    Left = null;
    Right = null;
    public T Data
    set { data = value; }
    get { return data; }
    in our daily program where we can use btree to store and retrieve data? so please all share your idea how you guys use btree in your program in real life application development. thanks

    "in our daily program where we can use btree to store and retrieve data?"
    Given that your example mentions IComparable I suppose you're talking specifically about binary search trees, not any binary tree. In that case it's unlikely that you'll see anyone using a binary tree directly. People use collections such as SortedDictionary and
    such collections are usually implemented using binary search trees.
    Note that btree isn't a good abbreviation for binary tree, there is such a data structure called B-Tree and it's not the same thing as binary tree. Incidentally B-Trees are also used for searching - databases use them for indexes and filesystems
    use them to store directory entries.
    @Joel Engineer: "Binary trees structures are built into the Net Library Hash Class"
    Binary trees and hash tables have nothing in common.

  • 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.

  • MorseCode Binary Tree

    So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
    For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
    I am sorry for such sloppy code.. I have been changing and rearranging too much.
    import java.io.*;
    import java.util.*;
    public class MorseCode extends BinaryTree{
         static BufferedReader in;
         static BinaryTree<String> bT = new BinaryTree<String>();
    /*     public static void loadTree() throws FileNotFoundException, IOException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
         public static String decode(Character c) throws IOException{
              if(c.equals("null")){
                   return "";
              }else if(c.equals(" ")){
                   return " ";
              }else{
                   return (":" + find(c));
         public static String find(Character c) throws IOException, FileNotFoundException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
              Queue<BinaryTree> data = new LinkedList<BinaryTree>();
              BinaryTree<String> tempTree = bT;
              String temp = null;
              Character tempChar = null;
              data.offer(tempTree);
              while(!data.isEmpty()){
                   tempTree = data.poll();
                   temp = tempTree.getData();
                   tempChar = temp.charAt(0);
                   if(tempChar.equals(c)){
                        break;
                   data.offer(tempTree.getRightSubtree());
                   data.offer(tempTree.getLeftSubtree());
              return temp.substring(2);               
         public static void main(String[] args) throws FileNotFoundException, IOException{
              Scanner scan = new Scanner(new FileReader("encode.in.txt"));
              String s = "";
              String temp = "";
              while(scan.hasNextLine()){
                    temp = scan.nextLine();
                    for(int i = 0; i < temp.length(); i++){
                         s = s + decode(temp.charAt(i));
              System.out.println(s);
    /** Class for a binary tree that stores type E objects.
    *   @author Koffman and Wolfgang
    class BinaryTree <E> implements Serializable
      //===================================================
      /** Class to encapsulate a tree node. */
      protected static class Node <E> implements Serializable
        // Data Fields
        /** The information stored in this node. */
        protected E data;
        /** Reference to the left child. */
        protected Node <E> left;
        /** Reference to the right child. */
        protected Node <E> right;
        // Constructors
        /** Construct a node with given data and no children.
            @param data The data to store in this node
        public Node(E data) {
          this.data = data;
          left = null;
          right = null;
        // Methods
        /** Return a string representation of the node.
            @return A string representation of the data fields
        public String toString() {
          return data.toString();
      }//end inner class Node
      //===================================================
      // Data Field
      /** The root of the binary tree */
      protected Node <E> root;
      public BinaryTree()
        root = null;
      protected BinaryTree(Node <E> root)
        this.root = root;
      /** Constructs a new binary tree with data in its root,leftTree
          as its left subtree and rightTree as its right subtree.
      public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
        root = new Node <E> (data);
        if (leftTree != null) {
          root.left = leftTree.root;
        else {
          root.left = null;
        if (rightTree != null) {
          root.right = rightTree.root;
        else {
          root.right = null;
      /** Return the left subtree.
          @return The left subtree or null if either the root or
          the left subtree is null
      public BinaryTree <E> getLeftSubtree() {
        if (root != null && root.left != null) {
          return new BinaryTree <E> (root.left);
        else {
          return null;
      /** Return the right sub-tree
            @return the right sub-tree or
            null if either the root or the
            right subtree is null.
        public BinaryTree<E> getRightSubtree() {
            if (root != null && root.right != null) {
                return new BinaryTree<E>(root.right);
            } else {
                return null;
         public String getData(){
              if(root.data == null){
                   return "null";
              }else{
                   return (String) root.data;
      /** Determine whether this tree is a leaf.
          @return true if the root has no children
      public boolean isLeaf() {
        return (root.left == null && root.right == null);
      public String toString() {
        StringBuilder sb = new StringBuilder();
        preOrderTraverse(root, 1, sb);
        return sb.toString();
      /** Perform a preorder traversal.
          @param node The local root
          @param depth The depth
          @param sb The string buffer to save the output
      private void preOrderTraverse(Node <E> node, int depth,
                                    StringBuilder sb) {
        for (int i = 1; i < depth; i++) {
          sb.append("  ");
        if (node == null) {
          sb.append("null\n");
        else {
          sb.append(node.toString());
          sb.append("\n");
          preOrderTraverse(node.left, depth + 1, sb);
          preOrderTraverse(node.right, depth + 1, sb);
      /** Method to read a binary tree.
          pre: The input consists of a preorder traversal
               of the binary tree. The line "null" indicates a null tree.
          @param bR The input file
          @return The binary tree
          @throws IOException If there is an input error
      public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
        // Read a line and trim leading and trailing spaces.
        String data = bR.readLine().trim();
        if (data.equals("null")) {
          return null;
        else {
          BinaryTree < String > leftTree = readBinaryTree(bR);
          BinaryTree < String > rightTree = readBinaryTree(bR);
          return new BinaryTree < String > (data, leftTree, rightTree);
      }//readBinaryTree()
      /*Method to determine the height of a binary tree
        pre: The line "null" indicates a null tree.
          @param T The binary tree
          @return The height as integer
      public static int height(BinaryTree T){
            if(T == null){
               return 0;
          }else{
               return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
      public static String preOrderTraversal(BinaryTree<String> T){
          String s = T.toString();
          String s2 = "";
          String temp = "";
          Scanner scan = new Scanner(s);
          while(scan.hasNextLine()){
               temp = scan.nextLine().trim();
               if(temp.equals("null")){
                   s2 = s2;
              }else{
                   s2 = s2 + " " + temp;
          return s2;
    }//class BinaryTree

    As well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
    public static void main(String[] args) throws FileNotFoundException, IOException{
        //Scanner scan = new Scanner(new FileReader("encode.in.txt"));
        Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
    public static String decode(Character c) throws IOException{
        if(c.equals("null")){
    c is a Character so it will never be the case that it is equal to the string n-u-l-l.
    Perhaps the behaviour of each of these methods needs to be (documented and) tested.

Maybe you are looking for

  • TS2776 I cannot get my IPhone to recognize my new computer; it's still looking for the old one.

    My IPhone won't sync with a new windows 8 computer.  It's still looking for the old one.  How in the he11 do you change the name of the PC the IPhone looks for?

  • Save excel chart as image (activeX)

    Hi community, I have to generate couple thousands xls files which have some data and a chart on the first sheet. Once the files are generated I'd like to sweep thru all of them and save the chart as an image (BMP, GIF, PNG, doesnt matter). I have no

  • Which z3 compact suite for osx 10.5.8?

    Hi! The latest version of sony suite for mac is compatible for osx 10.7.. I have osx 10.5.8, which suite can I use? I tried with kies, bat doesn't work. Suggestions? Thanks!!!!

  • Batch changing iPhoto photo dates.

    I've imported several thousand scanned photos into iPhoto 7.1.3, and changed the dates to the dates they was taken either by modifying the information window, or by using batch date change. My intention was to modify the original files so that export

  • Airport express not found after setup

    I have a maddening situation. At the beginning of setting up my airport extreme, the computer has no problem finding the wireless device. However, after the A/E is configured and added to my current network (linksys router), the computer can't find t