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

Similar Messages

  • Deep cloning a Binary Tree

    Hi, I have a class called DigitalTree that acts like a binary tree, storing nodes that each have a "key" which is a long value, and then puts each node into the tree in its correct place, binary tree style. I am trying to deep clone the tree, but for some reason my recursive cloning method isn't working. If anyone can see a problem in my code or has any tips for me, it would be greatly appreciated. Thanks.
    public Object clone()
           DigitalTree<E> treeClone = null;
           try
               treeClone = (DigitalTree<E>)super.clone();
           catch(CloneNotSupportedException e)
               throw new Error(e.toString());
           cloneNodes(treeClone, this.root, treeClone.root);
           return treeClone;
       private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
           if(treeClone.size == 0)
               cloneNode = null;
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
           else if(currentNode != null)
               cloneNode = (Node<E>)currentNode.clone();
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
       }In the Node class:
    public Object clone()
              Node<E> nodeClone = null;
              try
                   nodeClone = (Node<E>)super.clone();
              catch(CloneNotSupportedException e)
                   throw new Error(e.toString());
              return nodeClone;
           }

    Hello jssutton
    Your question inspired me to try my own binary tree and cloning. My cloning algorithm is similar to yours but with one difference.
    In my class Tree defined as:
    class Tree<T extends Comparable>
    I have:
        private void deepCopyLeft(TreeNode<T> src, TreeNode<T> dest) {
            if (src == null) return;
            dest.mLeft = new TreeNode<T>(src.mValue);
            deepCopyLeft(src.mLeft, dest.mLeft);
            deepCopyRight(src.mRight, dest.mLeft);
        private void deepCopyRight(TreeNode<T> src, TreeNode<T> dest) {
            if (src == null) return;
            dest.mRight = new TreeNode<T>(src.mValue);
            deepCopyLeft(src.mLeft, dest.mRight);
            deepCopyRight(src.mRight, dest.mRight);
        public Tree<T> deepCopy() {
            if (root == null) return new Tree<T>();
            TreeNode<T> newRoot = new TreeNode<T>(root.mValue);
            deepCopyLeft(root.mLeft, newRoot);
            deepCopyRight(root.mRight, newRoot);
            return new Tree<T>(newRoot);
        }Its a similar recursive idea, but with 2 extra functions. I hope that helps. I don't have time right now to pinpoint the problem in your routine. Good luck.

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

  • 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

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

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

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

  • 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

  • Succinct encoding for binary tree with n nodes...

    How do I find all possible bit strings (Succinct encoding) for a binary tree with order n? Can anybody give me an algorithm?

    I associate the order of a tree with some sort of a search or traversal. What do you mean by a "+tree with order n+"?
    Could you perhaps give an example of what you're looking for?

  • Binary Tree Help

    I have a project where I need to build a binary tree with random floats and count the comparisons made. The problem I'm having is I'm not sure where to place the comaprison count in my code. Here's where I have it:
    public void insert(float idata)
              Node newNode = new Node();
              newNode.data = idata;
              if(root==null)
                   root = newNode;
              else
                   Node current = root;
                   Node parent;
                   while(true)
                        parent = current;
                        if(idata < current.data)
                             comp++;
                             current = current.leftc;
                             if(current == null)
                                  parent.leftc = newNode;
                                  return;
                        else
                             current = current.rightc;
                             if(current == null)
                                  parent.rightc = newNode;
                                  return;
         }//end insertDo I have it in the right place? Also, if I'm building the tree for 10,000 numbers would I get a new count for each level or would I get one count for comparisons?? I'd appreciate anyone's help on this.

    You never reset the comp variable, so each timeyou
    insert into the tree, it adds the number ofinserts
    to the previous value.Yes, or something like that. I'm not sure what theOP
    really means.Yeah, it's hard to be sure without seeing the rest of
    the code.Sorry, I thought I had already posted my code for you to look at.
    Here's a copy of it:
    class Node
         public float data;
         public Node leftc;
         public Node rightc;
    public class Btree
         private Node root;
         private int comp;
         public Btree(int value)
              root = null;
         public void insert(float idata)
              Node newNode = new Node();
              newNode.data = idata;
              if(root==null)
                   root = newNode;
              else
                   Node current = root;
                   Node parent;
                   while(true)
                        parent = current;
                        comp++;
                        if(idata < current.data)
                             current = current.leftc;
                             if(current == null)
                                  parent.leftc = newNode;
                                  return;
                        else
                             current = current.rightc;
                             if(current == null)
                                  parent.rightc = newNode;
                                  return;
         }//end insert
        public void display()
             //System.out.print();
             System.out.println("");     
             System.out.println(comp);
    } //end Btree
    class BtreeApp
         public static void main(String[] args)
              int value = 10000;
              Btree theTree = new Btree(value);
              for(int j=0; j<value; j++)
                   float n = (int) (java.lang.Math.random() *99);
                   theTree.insert(n);
                   theTree.display();
    }

  • Binary tree problems.

    hi everyone.
    I have an assignment to use a binary search tree whose nodes hold a reference to a string, and also to an int which is the count of how many times that word occurs in an input file, then it traverses the tree and prints out the result to an output file.
    But when I compile, I get this one error, which I'm not sure how to fix.
    the error says:
    WordCount2.java:142: displayNode(java.lang.String,int) in Node cannot be applied to () localRoot.displayNode();
    and here's he code:
    import java.io.*;
    import java.util.*;
    import java.util.StringTokenizer;
    import java.lang.String.*;
    class WordCount2
    public static void main (String [] args) throws IOException
    StringTokenizer tokenizer;
    String inputpath, outputpath;
    String line = "";
    String str = "";
    Tree tree = new Tree();
    int i = 0;
    int count = 0;
    Node now = new Node();
    BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the pathname of the input file: ");
    inputpath = stdin.readLine();
    System.out.println("Enter the pathname of the output file: ");
    outputpath = stdin.readLine();
    FileReader textFile1 = new FileReader(inputpath);
    BufferedReader inputFile = new BufferedReader (textFile1);
    FileWriter textFile2 = new FileWriter(outputpath);
    PrintWriter outputFile = new PrintWriter(textFile2);
    while ((line = inputFile.readLine()) != null)
    tokenizer = new StringTokenizer(line, " ");
    while (tokenizer.hasMoreTokens())
    String s = tokenizer.nextToken().toLowerCase();
    tree.insert(s, i);
    tree.inOrderTraverse(now);
    class Node
    public String sData;
    public int iData;
    public Node leftChild;
    public Node rightChild;
    public Node()
    sData = "";
    iData = 0;
    public void displayNode(String s, int i) throws IOException
    String file = "test1.txt";
    FileReader fr = new FileReader (file);
    BufferedReader inFile = new BufferedReader(fr);
    String line = inFile.readLine();
    String file2 = "outfile.txt";
    FileWriter fw = new FileWriter (file2);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);
    outFile.print (s);
    outFile.print (" - ");
    outFile.print (i);
    outFile.flush();
    class Tree
    private Node root;
    public Tree()
    root = null;
    public void insert(String sd, int id)
    Node newNode = new Node();
    newNode.sData = sd;
    newNode.iData = id;
    if (root == null)
    root = newNode;
    else
    Node current = root;
    Node parent;
    while (true)
    parent = current;
    if ((newNode.sData).compareTo(current.sData) < 0)
    current = current.leftChild;
    if (current == null)
    parent.leftChild = newNode;
    return;
    else if((newNode.sData).compareTo(current.sData) == 0)
    increment(newNode.iData);
    else
    current = current.rightChild;
    if(current == null)
    parent.rightChild = newNode;
    return;
    public void inOrderTraverse (Node localRoot)
    if (localRoot != null)
    inOrderTraverse(localRoot.leftChild);
    localRoot.displayNode();
    inOrderTraverse(localRoot.rightChild);
    private int increment(int i)
    return i++;
    any help is greatly appreciated! thanks!

    ok, thanks a lot!
    so i was able to fix that, and it compiles, but when I run it, it gets stuck after i enter the name of the input and output files. anyone have any idea why it's doing that? I can't figure it out...
    here's the edited code:
    import java.io.*;
    import java.util.*;
    import java.util.StringTokenizer;
    import java.lang.String.*;
    class WordCount2
    public static void main (String [] args) throws IOException
    StringTokenizer tokenizer;
    String inputpath, outputpath;
    String line = "";
    String str = "";
    Tree tree = new Tree();
    int i = 0;
    int count = 0;
    Node now = new Node();
    BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the pathname of the input file: ");
    inputpath = stdin.readLine();
    System.out.println("Enter the pathname of the output file: ");
    outputpath = stdin.readLine();
    FileReader textFile1 = new FileReader(inputpath);
    BufferedReader inputFile = new BufferedReader (textFile1);
    FileWriter textFile2 = new FileWriter(outputpath);
    PrintWriter outputFile = new PrintWriter(textFile2);
    while ((line = inputFile.readLine()) != null)
    tokenizer = new StringTokenizer(line, " ");
    while (tokenizer.hasMoreTokens())
    String s = tokenizer.nextToken().toLowerCase();
    tree.insert(s, i);
    tree.inOrderTraverse(now);
    class Node
    public String sData;
    public int iData;
    public Node leftChild;
    public Node rightChild;
    public Node()
    sData = "";
    iData = 0;
    public void displayNode(String s, int i) throws IOException
    String file = "test1.txt";
    FileReader fr = new FileReader (file);
    BufferedReader inFile = new BufferedReader(fr);
    String line = inFile.readLine();
    String file2 = "outfile.txt";
    FileWriter fw = new FileWriter (file2);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);
    outFile.print (s);
    outFile.print (" - ");
    outFile.print (i);
    outFile.flush();
    class Tree
    private Node root;
    public Tree()
    root = null;
    public void insert(String sd, int id)
    Node newNode = new Node();
    newNode.sData = sd;
    newNode.iData = id;
    if (root == null)
    root = newNode;
    else
    Node current = root;
    Node parent;
    while (true)
    parent = current;
    if ((newNode.sData).compareTo(current.sData) < 0)
    current = current.leftChild;
    if (current == null)
    parent.leftChild = newNode;
    return;
    else if((newNode.sData).compareTo(current.sData) == 0)
    increment(newNode.iData);
    else
    current = current.rightChild;
    if(current == null)
    parent.rightChild = newNode;
    return;
    public void inOrderTraverse (Node localRoot) throws IOException
    String s = "";
    int i = 0;
    if (localRoot != null)
    inOrderTraverse(localRoot.leftChild);
    localRoot.displayNode(s, i);
    inOrderTraverse(localRoot.rightChild);
    private int increment(int i)
    return i++;
    thanks again!

  • 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

  • Traverse a binary tree from root to every branch

    I have a couple of other questions. I need to get all the different combinations of a binary tree and store them into a data structure. For the example in the code below, the combinations would be:
    1) Start, A1, A2, A3, B1, B2, B3
    2) Start, A1, A2, B1, A3, B2, B3
    3) Start, A1, A2, B1, B2, A3, B3
    4) Start, A1, A2, B1, B2, B3, A3
    5) Start, A1, B1, A2, A3, B2, B3
    etc.
    I understand that this is very similar to the preorder traversal, but preorder does not output the parent nodes another time when the node splits into a left and right node. Any suggestions?
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package binarytreetest;
    import java.util.ArrayList;
    import java.util.Iterator;
    * @author vluong
    public class BinaryTreeTest {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            int countA = 0;
            int countB = 0;
            ArrayList listA = new ArrayList();
            ArrayList listB = new ArrayList();
            listA.add("A1");
            listA.add("A2");
            listA.add("A3");
            listB.add("B1");
            listB.add("B2");
            listB.add("B3");
            //listB.add("B1");
            Node root = new Node("START");
            constructTree(root, countA, countB, listA, listB);
            //printInOrder(root);
            //printFromRoot(root);
        public static class Node{
            private Node left;
            private Node right;
            private String value;
            public Node(String value){
                this.value = value;
        public static void constructTree(Node node, int countA, int countB, ArrayList listA, ArrayList listB){
            if(countA < listA.size()){
                if(node.left == null){
                    System.out.println("There is no left node. CountA is " + countA);
                    System.out.println("Created new node with value: " + listA.get(countA).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.left = new Node(listA.get(countA).toString()); 
                    constructTree(node.left, countA+1, countB, listA, listB);   
                }else{
                    System.out.println("There is a left node. CountA + 1 is " + countA+1);
                    constructTree(node.left, countA+1, countB, listA, listB);   
            if(countB < listB.size()){
                if(node.right == null){
                    System.out.println("There is no right node. CountB is " + countB);
                    System.out.println("Created new node with value: " + listB.get(countB).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.right = new Node(listB.get(countB).toString());
                    constructTree(node.right, countA, countB+1, listA, listB);
                }else{
                    System.out.println("There is a right node. CountB + 1 is " + countB+1);
                    constructTree(node.right, countA, countB+1, listA, listB);
        }My second question is, if I need to add another list (listC) and find all the combinations of List A, listB and list C, is it correct to define the node class as
    public static class Node{
            private Node left;
            private Node mid;
            private Node right;
            private String value;
            public Node(String value){
                this.value = value;
        }Node left = listA, Node mid = listB, Node right = listC
    The code for the 3 lists is below.
    3 lists (A, B, C):
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package binarytreetest;
    import java.util.ArrayList;
    * @author vluong
    public class BinaryTreeTest {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            insert(root, "A1");
            insert(root, "A2");
            insert(root, "B1");
            insert(root, "B2"); 
            insert(root, "A2");
            int countA = 0;
            int countB = 0;
            int countC = 0;
            ArrayList listA = new ArrayList();
            ArrayList listB = new ArrayList();
            ArrayList listC = new ArrayList();
            listA.add("A1");
            listA.add("A2");
            //listA.add("A3");
            listB.add("B1");
            listB.add("B2");
            //listB.add("B3");
            //listB.add("B1");
            listC.add("C1");
            listC.add("C2");
            Node root = new Node("START");
            constructTree(root, countA, countB, countC, listA, listB, listC);
            //ConstructTree(root, countA, countB, listA, listB);
            //ConstructTree(root, countA, countB, listA, listB);
            printInOrder(root);
            //printFromRoot(root);
        public static class Node{
            private Node left;
            private Node mid;
            private Node right;
            private String value;
            public Node(String value){
                this.value = value;
        public static void constructTree(Node node, int countA, int countB, int countC, ArrayList listA, ArrayList listB, ArrayList listC){
            if(countA < listA.size()){
                if(node.left == null){
                    System.out.println("There is no left node. CountA is " + countA);
                    System.out.println("Created new node with value: " + listA.get(countA).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.left = new Node(listA.get(countA).toString()); 
                    constructTree(node.left, countA+1, countB, countC, listA, listB, listC);   
                }else{
                    System.out.println("There is a left node. CountA + 1 is " + countA+1);
                    constructTree(node.left, countA+1, countB, countC, listA, listB, listC);   
            if(countB < listB.size()){
                if(node.mid == null){
                    System.out.println("There is no mid node. CountB is " + countB);
                    System.out.println("Created new node with value: " + listB.get(countB).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.mid = new Node(listB.get(countB).toString());
                    constructTree(node.mid, countA, countB+1, countC, listA, listB, listC);
                }else{
                    System.out.println("There is a right node. CountB + 1 is " + countB+1);
                    constructTree(node.mid, countA, countB+1, countC, listA, listB, listC);
            if(countC < listC.size()){
                if(node.right == null){
                    System.out.println("There is no right node. CountC is " + countC);
                    System.out.println("Created new node with value: " + listC.get(countC).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.right = new Node(listC.get(countC).toString());
                    constructTree(node.right, countA, countB, countC+1, listA, listB, listC);
                }else{
                    System.out.println("There is a right node. CountC + 1 is " + countC+1);
                    constructTree(node.mid, countA, countB, countC+1, listA, listB, listC);
        }Thank you in advance!

    It looks to me like you are interleaving two lists. It looks like you are doing this while leaving the two subsequences in their original order.
    If that is in fact what you are doing, then this is just a combinatorics problem. Here is psuedo code (NOT java!)
    List path = new List();
    show(List A, int a, List B, int b, path){
      if(a >= A.length() && b >= b.length()){
        spew(path);
      } else {
        if(a < A.length()){path.push(A[a]); show(A,a+1,B,b,); path.pop();}
        if(b < B.length()){path.push(B); show(A,a,B,b+1,); path.pop();}
    show(A, 0, B, 0);
    In order to interleave 3 lists, you would add C and c arguments to the function and you would add one more line in the else block.

  • Adding to a Linked Complete Binary Tree

    Hi all,
    I am having major trouble trying to grasp the concept behind adding to a Complete Binary Tree (linked structure). It is part of a much larger assignment that uses a Heap Priority Queue and I am genuinely stuck. I have noticed that there seems to be some sort of strike going on so I wont expect a reply to this.
    I understand that Binary Tree's are useful because of their recursive nature, does the process of adding use recursion also. My mind is a mess at the moment so forgive the rambling. My problem exists when I go to add after a right child on a lower level(anything below level 3). I have come to the conclusion that I it is impossible to continue with my adding method and that I should scrap it. Can anyone point anything relevant out to me? I'd appreciate it, thank you.
    public class LinkedBT implements CompleteBT
         private BTNode root;          //a reference to the root node
         private BTNode current;          //a reference to the last inserted node
         private BTNode firstNodeInLevel; //a reference to the first node in the level
         private int size;               //keeps track of the size of the BT
         private int currentLevel;
         private int leafCount;
         public LinkedBT()
              root = null;     //instantiate instance variables
              current = null;
              size = 0;
              currentLevel = 0;     //indicates that there are no nodes
              leafCount = 0;
              firstNodeInLevel = null;
         public boolean isEmpty()     
              return (root==null);
         public int size()
              return size;
         public void add(Object obj, int priority)
              BTNode tempNode = new BTNode(obj, priority);
              tempNode.parent = current;                                   //set the parent of the node to current
              if(isEmpty())                                             //if the tree is empty then make a new BTNode and give it the root reference
                   root = tempNode;     
                   current = root;                                        //make current reference to the root node
                   size++;
                   currentLevel++;                //increments currentLevel
                   return;                          //return control to calling method
              if(current.childrenFull!=true)          //if the current node has available children positions then check left and right and add BTNode appropriately
                   if(current.leftChild==null)
                        if(leafCount==0)     //if this is the first node to be added on any given level then.....
                             firstNodeInLevel = tempNode;     //.....store a reference to it for future adding purposes
                        current.leftChild = tempNode;     //adds BTNode to left child
                        leafCount++;
                   else
                        current.rightChild = tempNode;          //add BTNode to right child
                        leafCount++;
                        current.childrenFull = true;          //after adding the right child set the childrenFull property true NECESSARY?????
                        if(Math.pow(2, currentLevel)==leafCount)     //IF THIS EVALS TO TRUE THEN THE MAX NUMBER OF LEAVES FOR THAT LEVEL IS REACHED
                             currentLevel++;     //increment the level
                             leafCount = 0;     //reset the leaf count
                             current = firstNodeInLevel;          //change current to the furthest leaf on the left
                        else     //ELSE NEED TO GO BACK UP AND FIND NEXT FEASIBLE POSITION
                             //while(current.parent.rightChild.leftChild.)----------------THIS DOESNT WORK WHEN THE TREE GETS BIGGER
                                  //current = current.parent; //set current to next feasible position
              size++;
         public Object getRoot()
              return root;
         public void heapSort()
         private class BTNode
              private Object value;
              private int key;
              private BTNode parent;
              private BTNode leftChild;
              private BTNode rightChild;
              private boolean childrenFull;      //initially false, when both children are occupied then change to true
              private BTNode(Object obj, int priority)     //constructor accepts the value and the priority key
                   value = obj;          
                   key = priority;
                   parent = null;
                   leftChild = null;
                   rightChild = null;
                   childrenFull = false;
              public boolean hasNoChildren()
                   return(leftChild==null && rightChild==null);     //returns true if the node has no children
    }

    Currently working on setting the Linked Servers Security properties. Added the SQLAgent in the" Local server login to remote server login mappings:". The SQLAgent is the only entry in the grid. The SQLAgent has the Remote User and Remote Password
    of the AS400. Then below have "Not be made" for "For a login not defined in the lst above, connections will:".
    So provided that the SQL Admin only gives SQL Job create, Job Alter and Alter Linked Server to user/groups that he wants to use the linked server the Admin can control access to the linked server.
    Any thoughts?

  • 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

Maybe you are looking for