Print empty nodes in a Huffman binary Tree

Hi,
I have constructed a binary huffman tree, and I need to print the empty nodes as a character '-'. As I am using the array structure to build the huffman tree, I am very confused how I can go about it. This is my code. Any help will be appreciated:
import java.util.*;
import java.io.*;
import java.lang.*;
public class Huffman
    static char letters;
    static int frequency;
    static char frequency1;
    static int alphabet;
    static char frqtable [][];
    static char treetable[][];
    static TreeNode myTree[];
    static int i = 0;
    static int j = 0;
    static Scanner in = new Scanner(System.in);
    static int index = 0;
    static Vector temp = new Vector();
    static String finalarray[];
    public static void main (String args[])throws IOException{
        setFrequencyTable();
        treetable = frqtable;
        sortArray(treetable);
        buildHuffmanTree(treetable, alphabet);
       // printGeneralTree();
     public static void setFrequencyTable() throws IOException{
        System.out.println ("Please enter number of distinct alphabet");
        alphabet = in.nextInt();
        frqtable = new char[alphabet][2];
       for (int count = 0; count<alphabet; count++){
            System.out.println ("Enter the character");
            letters = (char) System.in.read();
            frqtable[i][j] = letters;
            System.out.println ("Enter frequency");
            frequency = in.nextInt();
            frequency1 = Integer.toString(frequency).charAt(0); ;
            frqtable[i][j+1] = frequency1;
            i = i+1;
            j = 0;
    public static void sortArray (char[][]treetable){
        char templetter;
        char tempfrq;
      for (int j=0; j < frqtable.length; j++) {
        for (int i=0; i < frqtable.length-1; i++) {
              if((treetable[1]) < (treetable[i+1][1])){
tempfrq = (treetable[i][1]);
templetter = (treetable[i][0]);
(treetable[i][1]) = (treetable[i+1][1]);
(treetable[i][0]) = (treetable[i+1][0]);
(treetable[i+1][1]) = tempfrq;
(treetable[i+1][0]) =templetter;
public static void levelorderTraversal(TreeNode root) {
levelorderHelper( root);
System.out.println();
private static void levelorderHelper( TreeNode node ) {
if( node == null )
return;
queue( node ); // queues root
qLeftqRight( index ); // queues Left/Right node of the node at 'index'
printIt(); // prints contents of queue
private static boolean queue( TreeNode n ) {
if( n != null ){ // if child exists, queue it
temp.addElement( n );
return true;
}else{
return false;
private static void qLeftqRight( int i ) { // for each queued node, queue its children
while( i < temp.size() ) {
TreeNode tmp = (TreeNode) temp.elementAt( i );
if (tmp.leaf == false){
queue( tmp.left );
queue( tmp.right );
i++;
private static void printIt() {
finalarray = new String[temp.size()];
for( int x = 0; x < temp.size(); x++ ) {
TreeNode t = (TreeNode) temp.elementAt( x );
if(t.ch == '\0'){
finalarray[x] = Integer.toString(t.count);
}else{
finalarray[x]=Character.toString(t.ch);
public static void buildHuffmanTree(char [][] treetable, int alphabet){
myTree = new TreeNode [alphabet];
TreeNode leftNode, rightNode;
TreeNode newNode = null;
for ( int i = 0; i < alphabet; i++ ){
myTree[i] = new TreeNode (treetable[i][0], Character.getNumericValue(treetable[i][1]));
for (int j =((myTree.length)-1); j>0; j--){
newNode = new TreeNode(myTree[j], myTree[j-1]);
myTree[j] = null;
myTree[j-1] =null;
if(j!=1){
for(int c = 0; c<(j-1); c++){
if(myTree[c].count <= newNode.count){
for(int x = alphabet-1; x>c; x--){
myTree[x] = myTree[x-1];
myTree[c] = newNode;
c= j-1;
}else{
myTree[0] = newNode;
levelorderTraversal(myTree[0]);
for(int i = 0; i < finalarray.length; i++){
System.out.println(finalarray[i]);
public class TreeNode{ 
final boolean leaf;
int count;
final char ch;
final TreeNode left,
right;
public TreeNode ( char ch, int count )
{  this.leaf  = true;
this.count = count;
this.ch = ch;
this.left = null;
this.right = null;
public char getChar(){
return ch;
public TreeNode ( TreeNode left, TreeNode right)
{  this.leaf  = false;
this.count = left.count + right.count;
this.left = left;
this.right = right;
this.ch ='\0';

doobybug wrote:
The finalarray actually prints the array.No, finalarray IS and array. It doesn't print anything.
The problem I think is with the TreeNode class where a leaf states the left and right nodes as null, but if I instantiate them to '-' they will continue to assign empty nodes until the program runs out of memory!!I don't know what you're saying here, but it sounds like you think that you have to set the Node to '-' in order to be able to print '-'. Really all you have to do is
for each node {
  if the node is empty {
    print -
  else {
    print whatever you print for non-empty nodes
}Or if an "empty" node is still a Node object, just with certain attribute values, then just create a toString method in the Node class that returns "-" when the Node is empty.
Really, if you know how to iterate over your nodes, and you know how to determine whether a node is empty, then your problem is solved, there's nothing else to it.

Similar Messages

  • A Binary Tree Implementation in ABAP

    Hi,
    Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
    Thanks,
    Manjula.

    Hi manjula,
    This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It. 
    It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing  through the tree.
    For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
    *& Report YBINTREE - Build/Print Binary Tree of numbers *
    report ybintree .
    types: begin of stree,
    value type i,
    left type ref to data,
    right type ref to data,
    end of stree.
    data: tree type stree.
    data: int type i.
    data: begin of rnd occurs 0,
    num type i,
    end of rnd.
    start-of-selection.
    do 100 times.
    generate random number between 0 and 100
    call function 'RANDOM_I4'
    exporting
    rnd_min = 0
    rnd_max = 100
    importing
    rnd_value = int.
    store numbers
    rnd-num = int.
    append rnd.
    build binary tree of random numbers
    perform add_value using tree int.
    enddo.
    stored numbers are sorted for comparison
    sort rnd by num.
    print sorted random numbers
    write: / 'Sorted Numbers'.
    write: / '=============='.
    skip.
    loop at rnd.
    write: rnd-num.
    endloop.
    skip.
    print binary tree. This should give the same result
    as the one listed from the internal table
    write: / 'Binary Tree List'.
    write: / '================'.
    skip.
    perform print_value using tree.
    skip.
    *& Form add_value
    text - Build tree with value provided
    -->TREE text
    -->VAL text
    form add_value using tree type stree val type i.
    field-symbols: <ltree> type any.
    data: work type stree.
    if tree is initial. "When node has no values
    tree-value = val. " assign value
    clear: tree-left, tree-right.
    create data tree-left type stree. "Create an empty node for left
    create data tree-right type stree. "create an empty node for right
    else.
    if val le tree-value. "if number is less than or equal
    assign tree-left->* to <ltree>. "assign the left node to fs
    call add_value recursively with left node
    perform add_value using <ltree> val.
    else. "if number is greater
    assign tree-right->* to <ltree>. "assign the right node to fs
    call add_value recursively with right node
    perform add_value using <ltree> val.
    endif.
    endif.
    endform. "add_value
    *& Form print_value
    text - traverse tree from left-mid-right order
    automatically this will be sorted list
    -->TREE text
    form print_value using tree type stree.
    field-symbols: <ltree> type any.
    if tree is initial. "node is empty
    else. "non-empty node
    assign tree-left->* to <ltree>. "left node
    perform print_value using <ltree>. "print left
    write: tree-value. "print the current value
    assign tree-right->* to <ltree>. "right node
    perform print_value using <ltree>. "print right
    endif.
    endform. "print_value
    pls reward if helps,
    regards.

  • Having trouble finding the height of a Binary Tree

    Hi, I have an ADT class called DigitalTree that uses Nodes to form a binary tree; each subtree only has two children at most. Each node has a "key" that is just a long value and is placed in the correct position on the tree determined by its binary values. For the height, I'm having trouble getting an accurate height. With the data I'm using, I should get a height of 5 (I use an array of 9 values/nodes, in a form that creates a longest path of 5. The data I use is int[] ar = {75, 37, 13, 70, 75, 90, 15, 13, 2, 58, 24} ). Here is my code for the whole tree. If someone could provide some tips or clues to help me obtain the right height value, or if you see anything wrong with my code, it would be greatly aprpeciated. Thanks!
    public class DigitalTree<E> implements Copyable
       private Node root;
       private int size;
       public DigitalTree()
           root = null;
           size = 0;
       public boolean add(long k)
           if(!contains(k))
                if(this.size == 0)
                    root = new Node(k);
                    size++;
                    System.out.println(size + " " + k);
                else
                    String bits = Long.toBinaryString(k);
                    //System.out.println(bits);
                    return add(k, bits, bits.length(), root);
                return true;
           else
               return false;
       private boolean add(long k, String bits, int index, Node parent)
           int lsb;
           try
               lsb = Integer.parseInt(bits.substring(index, index - 1));
           catch(StringIndexOutOfBoundsException e)
               lsb = 0;
           if(lsb == 0)
               if(parent.left == null)
                   parent.left = new Node(k);
                   size++;
                   //System.out.println(size + " " + k);
                   return true;
               else
                   return add(k, bits, index-1, parent.left);
           else
               if(parent.right == null)
                   parent.right = new Node(k);
                   size++;
                   //System.out.println(size + " " + k);
                   return true;
               else
                   return add(k, bits, index-1,  parent.right);
       public int height()
           int leftHeight = 0, rightHeight = 0;
           return getHeight(root, leftHeight, rightHeight);
       private int getHeight(Node currentNode, int leftHeight, int rightHeight)
           if(currentNode == null)
               return 0;
           //else
           //    return 1 + Math.max(getHeight(currentNode.right), getHeight(currentNode.left));
           if(currentNode.left == null)
               leftHeight = 0;
           else
               leftHeight = getHeight(currentNode.left, leftHeight, rightHeight);
           if(currentNode.right == null)
               return 1 + leftHeight;
           return 1 + Math.max(leftHeight, getHeight(currentNode.right, leftHeight, rightHeight));
       public int size()
           return size;
       public boolean contains(long k)
            String bits = Long.toBinaryString(k);
            return contains(k, root, bits, bits.length());
       private boolean contains(long k, Node currentNode, String bits, int index)
           int lsb;
           try
               lsb = Integer.parseInt(bits.substring(index, index - 1));
           catch(StringIndexOutOfBoundsException e)
               lsb = 0;
           if(currentNode == null)
               return false;
           else if(currentNode.key == k)
               return true;
           else
               if(lsb == 0)
                   return contains(k, currentNode.left, bits, index-1);
               else
                   return contains(k, currentNode.right, bits, index-1);
       public Node locate(long k)
            if(contains(k))
                String bits = Long.toBinaryString(k);
                return locate(k, root, bits, bits.length());
            else
                return null;
       private Node locate(long k, Node currentNode, String bits, int index)
           int lsb;
           try
               lsb = Integer.parseInt(bits.substring(index, index - 1));
           catch(StringIndexOutOfBoundsException e)
               lsb = 0;
           if(currentNode.key == k)
               return currentNode;
           else
               if(lsb == 0)
                   return locate(k, currentNode.left, bits, index-1);
               else
                   return locate(k, currentNode.right, bits, index-1);
       public Object clone()
           DigitalTree<E> treeClone = null;
           try
               treeClone = (DigitalTree<E>)super.clone();
           catch(CloneNotSupportedException e)
               throw new Error(e.toString());
           cloneNodes(treeClone, root, treeClone.root);
           return treeClone;
       private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
           if(treeClone.size == 0)
               cloneNode = null;
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
           else if(currentNode != null)
               cloneNode = currentNode;
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
       public void printTree()
           System.out.println("Tree");
       private class Node<E>
          private long key;
          private E data;
          private Node left;
          private Node right;
          public Node(long k)
             key = k;
             data = null;
             left = null;
             right = null;
          public Node(long k, E d)
             key = k;
             data = d;
             left = null;
             right = null;
          public String toString()
             return "" + key;
    }

    You were on the right track with the part you commented out; first define a few things:
    1) the height of an empty tree is nul (0);
    2) the height of a tree is one more than the maximum of the heights of the left and right sub-trees.
    This translates to Java as a recursive function like this:
    int getHeight(Node node) {
       if (node == null) // definition #1
          return 0;   
       else // definition #2
          return 1+Math.max(getHeight(node.left), getHeight(node.right));
    }kind regards,
    Jos

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

  • Binary Tree search and print methods

    Hello, I'm trying to create a binary tree from inputs of a user. I believe I have the tree set up right because it shows no errors, but I'm getting an error message with a line of code. I cannot figure out what I am doing wrong. Also, I need to create a print method, which prints the tree's entries and a search method which would search the tree for certain record.
    public class TreeNode 
          public static String empName = null;
          public static int empNumber;
          public static String nextRec = null;
              TreeNode left;
          String Name;
          int Number;
          TreeNode right;
          public static void main(String[] args)
             VRead in = new VRead();
             VWrite out = new VWrite();
             System.out.println("Enter Choice: ");
             System.out.println("A: Enter Employee Information.");
             System.out.println("B: Search For Employee.");
             System.out.println("C: Print Entire Tree.");
             System.out.println("D: Exit.");
             System.out.println("_______________________________");
             char command = in.readChar();
             System.out.println();
             switch (command)
                case 'A':
                case 'a':
                   inputInfo(in, out);           
                   break;
                case 'B':
                case 'b':
                   break;
                case 'C':
                case 'c':
                   break;
                case 'D':
                case 'd':
                   System.exit(0);
                   break;
          public static void inputInfo(VRead in, VWrite out)
             out.write("Enter Employee Name: ");
             empName = in.readString();
             out.write("Enter Employee Number: ");
             empNumber = in.readInt();
             System.out.println();
             System.out.println();
             System.out.println("Enter Choice: ");
             System.out.println("A: Enter Employee Information.");
             System.out.println("B: Search For Employee.");
             System.out.println("C: Print Entire Tree.");
             System.out.println("D: Exit.");
             System.out.println("_______________________________");
             char command = in.readChar();
             System.out.println();
             switch (command)
                case 'A':
                case 'a':
                   inputInfo(in, out);           
                   break;
                case 'B':
                case 'b':
                   break;
                case 'C':
                case 'c':
                             break;
                case 'D':
                case 'd':
                   System.exit(0);
                   break;
          public TreeNode(String empName, int empNumber)
             Name = empName;
             Number = empNumber;
             left = null;
             right = null;
          public class Tree
             TreeNode Root;
             public void Tree(String RootNode)   
        // Errors come from next line
                  Root = new TreeNode(RootNode, Name, Number);   
             public void Insert(String Name, int Number)
                InsertNode(Root, Name, Number);
             public void InsertNode(TreeNode t, String empName, int empNumber)
                if (t == null)
                   t = new TreeNode(empName, empNumber);
                else
                   if (empName.compareTo(t.Name) < 0)
                      InsertNode(t.left, empName, empNumber);
                   else if (empName.compareTo(t.Name) > 0)
                      InsertNode(t.right, empName, empNumber);
                   else if (empName.compareTo(t.Name) == 0)
                      System.out.println("Entered node that was already in Tree");
       }im sure its something simple, i seem to always look over the small stuff. But i could really use some help on the print and search method too

    Just having a quick look over it, and it looks like you are trying to add an extra argument in the TreeNode() method (unless there is a bit of overloading and there is a second treenode method in there) As it is TreeNode only accepts two argumets you have 3
    As for printing the tree you would need to flatten it, that is an in order traversal of the tree.
    FWIW
    I just finished a project at uni that involved at frist writing a BST and then an AVL tree. the full point of these things seems to be to keep students awake at night*
    *Before anyone flames, it's a joke
    G

  • How to Pretty Print a Binary Tree?

    I'm trying to display a Binary Tree in such a way:
    ________26
    ___13_________2
    1_______4 3_________1
    (without the underscores)
    however I cannot figure out the display method.
    class BinaryNode
              //Constructors
              BinaryNode leftChild, rightChild;
    Object data;
         BinaryNode()
    leftChild = null;
    data = null;
    rightChild = null;
              BinaryNode( Object d, BinaryNode left, BinaryNode right)
    leftChild = left;
    data = d;
    rightChild = right;
              //Height
              public static int Height(BinaryNode root)
    if (root == null)
    return 0;
    if ((Height(root.leftChild)) > Height(root.rightChild))
    return 1 + Height(root.leftChild);
    return 1 + Height(root.rightChild);
              //Count
    public static int Count(BinaryNode root)
    if(root==null)
    return 0;
    return 1 + Count(root.leftChild) + Count(root.rightChild);
              //Display
              public static void Display(BinaryNode root)
              int level = 2^(Level(root)-1)
              for (int i = 1; i<Height(root)+1; i++)
              System.out.printf("%-4s%
              Display(root, i);
              System.out.println();
              public static void Display(BinaryNode root, int level)
              if (root!=null)
              if(level==1)
              System.out.print(root.data + " ");
              else
              Display(root.leftChild, level-1);
              Display(root.rightChild, level-1);
              //Level
              public static int Level(BinaryNode root)
              if(root==null)
              return 0;
              if(root.leftChild == null && root.rightChild == null)
              return 1;
              return Level(root.leftChild) + Level(root.rightChild);
    Edited by: 815035 on Nov 23, 2010 12:27 PM

    The example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
    Unfortunately it is also quite difficult to accomplish using System.out.print statements.
    You have to print out the root of the tree first (its at the top)
    However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
    So you will need to traverse the tree at least twice.
    Once to work out the offsets, and again to print out the values.
    The working out of offsets would have to be a depth search traversal I think
    The printing of the values in this fashion would be a breadth first traversal.
    I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
    ie the root was on the left, the leaves of the tree on the right of the screen.
    That meant you could do an inorder depth traversal of the tree to just print it once.
    hope this helps,
    evnafets

  • How to eliminate empty node space from tree when rendered property is false

    Hi
    I have created a menu Tree for my ADF BC application while working in JDev 10.1.3.3.
    I have tried two methods, first is by creating a menu model as discussed in example in ADF Developers Guide Book Section 19.2.1. Second by creating two view objects and creating the menu tree from my database table.
    Depending on the logged in user I want to decide whether to show or not to show a menu tree option to the user. For this purpose I have implemented a function in a managed bean that calls a pl/sql stored procedure to decide if the user has access to a certain component. In first case I have set the rendered property of the menu item to #{menuTree.shown}, where shown is an attribute in the menu model whose value is properly set using java functions that call pl/sql function in turn. In second method, I have also tried to set the rendered property and calling a function that returns true or false based on if the user has access to the menu option.
    Problem
    When rendered property is returned as false, although the menu option is not displayed but an empty space is displayed in my tree and remaining nodes and/or menu options are displayed with an ugly gap.
    How I can remove this unwanted gap, is there a way?
    Regards,
    Amir
    1st option:
    My menu tree:
    <af:menuTree var="menuTree" value="#{menuModel.model}">
    <f:facet name="nodeStamp">
    <af:commandMenuItem text="#{menuTree.label}"
    action="#{menuTree.getOutcome}"
    _rendered="#{menuTree.shown}_"/>
    </f:facet>
    </af:menuTree>
    2nd option:
    <af:tree value="#{bindings.MainMenuView.treeModel}" var="node">
    <f:facet name="nodeStamp">
    <af:switcher facetName="#{node.hierType.name}">
    <f:facet name="MainMenuViewNode">
    <af:outputText value="#{node.Name}" _rendered="#{userInfo.mainNodeOk}"_ />
    </f:facet>
    <f:facet name="SubMenuViewNode">
    <af:commandLink text="#{node.Name}" _rendered="#{userInfo.mainNodeOk}_">
    <af:setActionListener from="#{node.destinationUrl}"
    to="#{menuTree.getOutcome}"/>
    </af:commandLink>
    </f:facet>
    </af:switcher>
    Edited by: Amir Khan on Jan 12, 2009 8:54 PM

    Hi,
    if this reproduces in JDeveloper 10.1.3.4 then this sounds like a bug that you should file
    Frank

  • Binary tree - counting nodes

    i have got a binary tree and i need to write a method which can count the number of leaves.
    i have written the code as
    static int countLeaves(BinaryNode node) {
            if (node == null) {
                return 0;
            else if (node.left == null && node.right == null) {
                return 1;
            return countLeaves(node.left) + countLeaves(node.right);
    }but, how can i put the method in the main funcion, i have tried
    int leafCount = countLeaves(root);it gives an error message "non-static variable root cannot be referenced from a static context". How can i solve this problem? Thank you.

    the code looks like:
    public class BinaryTree<AnyType>
        public BinaryTree( )
            root = null;
        public BinaryTree( AnyType rootItem )
            root = new BinaryNode<AnyType>( rootItem, null, null );
        public void printPreOrder( )
            if( root != null )
                root.printPreOrder( );
        public void printInOrder( )
            if( root != null )
               root.printInOrder( );
        public void printPostOrder( )
            if( root != null )
               root.printPostOrder( );
        public void makeEmpty( )
            root = null;
        public boolean isEmpty( )
            return root == null;
        public void merge( AnyType rootItem, BinaryTree<AnyType> t1, BinaryTree<AnyType> t2 )
            if( t1.root == t2.root && t1.root != null )
                System.err.println( "leftTree==rightTree; merge aborted" );
                return;
            if( this != t1 )
                t1.root = null;
            if( this != t2 )
                t2.root = null;
        public BinaryNode<AnyType> getRoot( )
            return root;
        private BinaryNode<AnyType> root;
        static int countLeaves(BinaryNode node) {
            if (node == null) {
                return 0;
            else if (node.left == null && node.right == null) {
                return 1;
            return countLeaves(node.left) + countLeaves(node.right);
        static public void main( String [ ] args )
            BinaryTree<Integer> t1 = new BinaryTree<Integer>( 1 );
            BinaryTree<Integer> t3 = new BinaryTree<Integer>( 3 );
            BinaryTree<Integer> t5 = new BinaryTree<Integer>( 5 );
            BinaryTree<Integer> t7 = new BinaryTree<Integer>( 7 );
            BinaryTree<Integer> t2 = new BinaryTree<Integer>( );
            BinaryTree<Integer> t4 = new BinaryTree<Integer>( );
            BinaryTree<Integer> t6 = new BinaryTree<Integer>( );
            t2.merge( 2, t1, t3 );
            t6.merge( 6, t5, t7 );
            t4.merge( 4, t2, t6 );
            // i want to run the method countLeaves here
            int leafCount = countLeaves(root);
            System.out.println("Number of leaves: "+leafCount);
    }

  • Binary Tree: Number of Nodes at a Particular Level

    Hi, I'm trying to teach myself about binary tree but am having trouble writing an algorithm. The algorithm that I'm trying to write is one that will take a binary tree and output the number of nodes at each level of the tree (maybe in an array).
    I have no trouble writing an algorithm that does a breadth-first traversal, but I have lots of trouble trying to determine where each level ends.
    Thanks for the help

    Try something like this:
    class BTree {
        BTreeNode root;
        public int numberOfNodesAtLevel(int level) {
            if(root == null) return -1;
            return numberOfNodesAtLevel(root, level);
        private int numberOfNodesAtLevel(BTreeNode node, int level) {
            if(level == 0) {
                return 1;
            } else {
                return (node.left  == null ? 0 : numberOfNodesAtLevel(node.left, level-1)) +
                       (node.right == null ? 0 : numberOfNodesAtLevel(node.right,level-1));
    }

  • Binary tree - a spesific node's height !

    hello !
    im looking for a method to deterine a certain node's hight in a binary tree (that is its distance from the root )
    please enlighten me on how to do this if you can
    thank you

    > Traverse the BT and with every step increase a
    counter. When you get to the node you're looking for,
    return the counter.
    Or just add an attribute to you TreeNode class which holds the value for the degree/height of the node.

  • Pretty print of a binary tree

    Hi, I have to pretty print a binary tree composed of "key" values like 75, 70, 15, 2, etc. I have no idea how to create a dynamic method that can output a tree in the order that they are in. The tree is supposed to look like this:
                  15      
                  37
                       13
             75
                       90
                                 58
                             2
                  70
                       24The 15 is supposed to be in the top middle of the tree. Can anyone give me any help or hints to get started? Thanks.

    I guess you mean this
             15
      13              37
    2            24           75
                        58       90
                          70

  • FINDING THE LARGEST NODE IN A BINARY TREE

    can anybody help me with a recursive function to find the LARGEST NODE IN A BINARY TREE if you are given the following specs. PLEASE NOTE THAT IT'S A BINARY TREE NOT A SEARCH TREE.
    Public class Node {
    Node left;
    Node right;
    int val;
    int Largest(Node r){
    }

    Naah, just studying and thinking it's an interesting
    task Well, I diagree.
    since each time the recursive function is
    called, variables you hve in the method will be over
    written with the new recursive call.So what? For variables that are valid inside the scope of the method: that's how it supposed to be. Vor variables with a larger scope: hand them over as an additional argument.

  • Suppressing empty nodes in ALV tree grid

    Hi,  I'm writing an ALV tree report with financial data broken down by cost element hierarchy. We've determined that the maximum number of levels in our hierarchy is seven so have to build the program to accept seven node levels. Most times when it runs it will find fewer than seven nodes.  Is there an easy to to suppress empty columns in the report so that the end user does not not see a bunch of empty nodes in the report?

    Expand or Collapse Branches or Hide Areas
    You are able to expand and collapse the branches of the tree structure individually or together. Beyond that you are able to make a node or an item completely invisible.
    Methods
    Function                                       Class                                   Method
    Expand individual branch               CL_SALV_NODE                  EXPAND 
    Collapse individual branch                                                        COLLAPSE
    Expand all branches                    CL_SALV_NODES                EXPAND_ALL
    Collapse all branches                                                              COLLAPSE_ALL
    Change visibility of a node            CL_SALV_NODE                  SET_VISIBLE
    Check whether the node is visible                                             IS_VISIBLE
    Change visibility of an item             CL_SALV_ITEM                 SET_VISIBLE
    Check whether the item is visible                                             IS_VISIBLE

  • CTE for Count the Binary Tree nodes

    i have the table structure like this :
    Create table #table(advId int identity(1,1),name nvarchar(100),Mode nvarchar(5),ReferId int )
    insert into #table(name,Mode,ReferId)values('King','L',0)
    insert into #table(name,Mode,ReferId)values('Fisher','L',1)
    insert into #table(name,Mode,ReferId)values('Manasa','R',1)
    insert into #table(name,Mode,ReferId)values('Deekshit','L',2)
    insert into #table(name,Mode,ReferId)values('Sujai','R',2)
    insert into #table(name,Mode,ReferId)values('Fedric','L',3)
    insert into #table(name,Mode,ReferId)values('Bruce','R',3)
    insert into #table(name,Mode,ReferId)values('paul','L',4)
    insert into #table(name,Mode,ReferId)values('walker','R',4)
    insert into #table(name,Mode,ReferId)values('Diesel','L',5)
    insert into #table(name,Mode,ReferId)values('Jas','R',5)
    insert into #table(name,Mode,ReferId)values('Edward','L',6)
    insert into #table(name,Mode,ReferId)values('Lara','R',6)
    select *from #table
    How do i write the CTE for count the Binary tree nodes on level basis. Here is the example,
    now,what i want to do is if i'm going to calculate the Count of the downline nodes.which means i want to calculate for '1' so the resultset which i'm expecting
    count level mode
    1 1 L
    1 1 R
    2 2 L
    2 2 R
    4 3 L
    2 3 R
    How do i acheive this,i have tried this
    with cte (advId,ReferId,mode,Level)
    as
    select advId,ReferId,mode,0 as Level from #table where advid=1
    union all
    select a.advId,a.ReferId,a.mode ,Level+1 from #table as a inner join cte as b on b.advId=a.referId
    select *From cte order by Level
    i hope its clear. Thank you

    See Itzik Ben-Gan examples for the subject
    REATE TABLE Employees
      empid   int         NOT NULL,
      mgrid   int         NULL,
      empname varchar(25) NOT NULL,
      salary  money       NOT NULL,
      CONSTRAINT PK_Employees PRIMARY KEY(empid),
      CONSTRAINT FK_Employees_mgrid_empid
        FOREIGN KEY(mgrid)
        REFERENCES Employees(empid)
    CREATE INDEX idx_nci_mgrid ON Employees(mgrid)
    SET NOCOUNT ON
    INSERT INTO Employees VALUES(1 , NULL, 'Nancy'   , $10000.00)
    INSERT INTO Employees VALUES(2 , 1   , 'Andrew'  , $5000.00)
    INSERT INTO Employees VALUES(3 , 1   , 'Janet'   , $5000.00)
    INSERT INTO Employees VALUES(4 , 1   , 'Margaret', $5000.00) 
    INSERT INTO Employees VALUES(5 , 2   , 'Steven'  , $2500.00)
    INSERT INTO Employees VALUES(6 , 2   , 'Michael' , $2500.00)
    INSERT INTO Employees VALUES(7 , 3   , 'Robert'  , $2500.00)
    INSERT INTO Employees VALUES(8 , 3   , 'Laura'   , $2500.00)
    INSERT INTO Employees VALUES(9 , 3   , 'Ann'     , $2500.00)
    INSERT INTO Employees VALUES(10, 4   , 'Ina'     , $2500.00)
    INSERT INTO Employees VALUES(11, 7   , 'David'   , $2000.00)
    INSERT INTO Employees VALUES(12, 7   , 'Ron'     , $2000.00)
    INSERT INTO Employees VALUES(13, 7   , 'Dan'     , $2000.00)
    INSERT INTO Employees VALUES(14, 11  , 'James'   , $1500.00)
    The first request is probably the most common one:
     returning an employee (for example, Robert whose empid=7) 
    and his/her subordinates in all levels. 
    The following CTE provides a solution to this request:
    WITH EmpCTE(empid, empname, mgrid, lvl)
    AS
      -- Anchor Member (AM)
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = 7
      UNION ALL
      -- Recursive Member (RM)
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees AS E
        JOIN EmpCTE AS M
          ON E.mgrid = M.empid
    SELECT * FROM EmpCTE
    Using this level counter you can limit the number of iterations
     in the recursion. For example, the following CTE is used to return 
    all employees who are two levels below Janet:
    WITH EmpCTEJanet(empid, empname, mgrid, lvl)
    AS
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = 3
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees as E
        JOIN EmpCTEJanet as M
          ON E.mgrid = M.empid
      WHERE lvl < 2
    SELECT empid, empname
    FROM EmpCTEJanet
    WHERE lvl = 2
    As mentioned earlier, CTEs can refer to
     local variables that are defined within the same batch.
     For example, to make the query more generic, you can use 
    variables instead of constants for employee ID and level:
    DECLARE @empid AS INT, @lvl AS INT
    SET @empid = 3 -- Janet
    SET @lvl   = 2 -- two levels
    WITH EmpCTE(empid, empname, mgrid, lvl)
    AS
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = @empid
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees as E
        JOIN EmpCTE as M
          ON E.mgrid = M.empid
      WHERE lvl < @lvl
    SELECT empid, empname
    FROM EmpCTE
    WHERE lvl = @lvl
    Results generated thus far might be returned (but are not guaranteed to be), 
    and error 530 is generated. You might think of using the MAXRECURSION option 
    to implement the request to return employees who are two levels below 
    Janet using the MAXRECURSION hint instead of the filter in the recursive member
    WITH EmpCTE(empid, empname, mgrid, lvl)
    AS
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = 1
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees as E
        JOIN EmpCTE as M
          ON E.mgrid = M.empid
    SELECT * FROM EmpCTE
    OPTION (MAXRECURSION 2)
    WITH EmpCTE(empid, empname, mgrid, lvl, sortcol)
    AS
      SELECT empid, empname, mgrid, 0,
        CAST(empid AS VARBINARY(900))
      FROM Employees
      WHERE empid = 1
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1,
        CAST(sortcol + CAST(E.empid AS BINARY(4)) AS VARBINARY(900))
      FROM Employees AS E
        JOIN EmpCTE AS M
          ON E.mgrid = M.empid
    SELECT
      REPLICATE(' | ', lvl)
        + '(' + (CAST(empid AS VARCHAR(10))) + ') '
        + empname AS empname
    FROM EmpCTE
    ORDER BY sortcol
    (1) Nancy
     | (2) Andrew
     |  | (5) Steven
     |  | (6) Michael
     | (3) Janet
     |  | (7) Robert
     |  |  | (11) David
     |  |  |  | (14) James
     |  |  | (12) Ron
     |  |  | (13) Dan
     |  | (8) Laura
     |  | (9) Ann
     | (4) Margaret
     |  | (10) Ina
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Queue for Binary Tree Node

    I need to create a simple Queue class for Binary Tree Node. The class consist of only enqueue and dequeue, I cannot use the Collection Interface though. But I have no idea how to do it. Below is my Binary Tree Node Class.
    public class BTNode {
         private customer     item;
         private BTNode     left;
         private BTNode     right;
         public BTNode() {// constructor
              item = null;
              left = right = null;
         public BTNode(customer newItem) {// constructor
              item = newItem.clone();
              left = right = null;
         public void setItem(customer newItem) {// set methods
              item = newItem.clone();
         public void setLeft(BTNode newLeft) {
              left = newLeft;
         public void setRight(BTNode newRight) {
              right = newRight;
         public customer getItem() {     // get methods
              return item;
         public BTNode getLeft() {
              return left;
         public BTNode getRight() {
              return right;
    public class Queue1 extends BTNode {
        public Queue1() {
            super();
        public void enqueue(BTNode newItem) {
        public void dequeue() {
    }

    public class Queue1 extends BTNode {Why do you think that the queue should extend BTNode?
    You probably want to aggregate a List.
    Kaj

Maybe you are looking for