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.

Similar Messages

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

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

  • Writting Methods of Binary Tree

    I am using java code to write some binary tree methods.
    Got stuck in some of the following methods.
    Hopefully i can get some help here.
    Public int width(){
    // Return the maximun number of nodes in each level
    Public boolean checkIsFullTree(){
    // Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full)
    Public boolean checkIsCompleteTree(){
    // Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full and is filled from left to right)
    at last
    Public int internalPathLength(){
    // Return The sum of all internal nodes of the paths from the root of an extended binary tree to each node.
    other words, the sum of all depths of nodes.
    Looking forawad to see some replies. Chrees

    I have came up with some ideas.
    Public boolean checkIsFullTree(TreeNode t, int currentHeight ) {
    int maxHeight = height(); // Maximum height.
    int currentHeight=currentHeight;
    if (t == null){
    return false;
    if (t.left() ! = null){
    currentHeight++;
    checkIsFullTree(t.left(), currentHeight);
    if (t.right() ! = null){
    currentHeight++;
    checkIsFullTree(t.right(), currentHeight);
    if ( t.left() == null && t.right() == null){
    if (currentHeight == maxHeight) {
    check = true;
    }else{
    check = false;
    But i am missing sometime here i guess.
    }

  • How to remember the path while traverse a binary tree?

    Hi, again, I have difficulty handling tree search problems.
    The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
    I think the signature should be:
    // The path contains only 0s and 1s. 0 means go left and 1 means go right.
    public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
    // the class Node only has two fields:
    Node{
    Node left;
    Node right;
    I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
    I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
    Anyone wants to help?

    Hi, JosAh,
    That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
    The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
    So I changed your code to be:
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    return search(root.right, node, path);
    }I simply tested it with
    Stack<Integer> path = new Stack<Integer>();
    System.out.println( root, root.right.right, path);
    root is the root of a complete binary tree with 7 nodes(4 leaves).
    Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
    Considerring , the right branch never pops, I changed it into
    Then I changed it to :
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right ) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    if (search(root.right, node, path) != null) return path;
    path.pop();
    return path;
    With the same test case, it returns [].
    I will keep working on it.
    Cheers,
    Message was edited by:
    since81
    Message was edited by:
    since81

  • 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

  • Getting the height of a binary tree

    So I am trying to create a method in my binary tree class that returns and integer that represents the height of the tree.
    I tried to do this recursively and it seems the numbers are close to the actual ones, but never exact and I haven't really been able to find out where the problem lies. This is my code:
    public int getHeight()
              int height;
              height = getHeightRecur(root);
              return height;
         public int getHeightRecur(BinTreeNode node)
              int theight;
              if(node == null)
                   theight = 0;
              else
                   theight = 1 + getMax(getHeightRecur(node.leftN), getHeightRecur(node.rightN));
              return theight;
         private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              if(y>x)
                   result = y;
              return result;
         }

    j2ee_ubuntu wrote:
    it may help at some extent..
    private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              else if(y>x)
                   result = y;
    else //when both are equal
    result =x; OR result = y;//You can use one of them
              return result;
         }Edited by: j2ee_ubuntu on Nov 6, 2008 12:30 AMWhy not just use [ Math.max|http://java.sun.com/javase/6/docs/api/java/lang/Math.html#max(int,%20int)] or write
    public static int max(int a, int b) {
        return (a >= b) ? a : b;
    }

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

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

  • 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

  • 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

  • Recover a Binary Tree

    Ok people I need help!
    I want to create, from a pre-order and in-order sequences, the post-order sequence! Obviously there are no repeated elements (characters from A to Z at this case).
    The tree root it's the first character from pre-order and after that it's easy to take left and right sequences.
    I found an interesting explanation: http://www.dcs.kcl.ac.uk/staff/pinz...st/html/l7.html
    I've tried everything to make it recursive I think that's the best way to do it but somehow I can't make it work! My last code:
    import java.io.*;
    import java.util.*;
    public class Problem
            static String readLn (int maxLg)  // utility function to read from stdin
                byte lin[] = new byte [maxLg];
                int lg = 0, car = -1;
                try
                    while (lg < maxLg)
                        car = System.in.read();
                        if ((car < 0) || (car == '\n')) break;
                        lin [lg++] += car;
                catch (IOException e)
                    return (null);
                if ((car < 0) && (lg == 0)) return (null);  // eof
                return (new String (lin, 0, lg));
            public static void main (String []args)
                    for (int set = Integer.parseInt(readLn(10).trim()); set != 0; set--)
                            StringTokenizer tok = new StringTokenizer(readLn(100).trim()," ");
                            String preOrd = tok.nextToken();
                            String inOrd = tok.nextToken();
                            char root = preOrd.charAt(0);
                            BinaryNode tree = new BinaryNode(root);
                            // Left and right from inOrd
                            tok = new StringTokenizer(inOrd,Character.toString(root));
                            String inOrdLeft = tok.nextToken();
                            String inOrdRight = tok.nextToken();
                            // Take left and right from preOrd
                            String preOrdLeft = preOrd.substring(1,inOrdLeft.length()+1);
                            String preOrdRight = preOrd.substring(inOrdLeft.length()+1);
                            tree.left = work (preOrdLeft, 0, inOrdLeft);
                            tree.right = work (preOrdRight, 0, inOrdRight);
                            tree.printPostOrder();
                            System.out.println();
            public static BinaryNode work (String preOrd, int preOrdPoint, String inOrd)
                    char    nodeChr = preOrd.charAt(preOrdPoint);
                    String  nodeStr = Character.toString(nodeChr);
                    //System.out.println("Root: "+nodeStr+" preOrd: "+preOrd+" inOrd: "+inOrd);
                    BinaryNode tempTree = new BinaryNode(nodeChr);
                    StringTokenizer tok = new StringTokenizer(inOrd,nodeStr);  
                    try
                            String newInOrdLeft = tok.nextToken();
                            if (newInOrdLeft.length() == 1) { tempTree.left = new BinaryNode(newInOrdLeft.toCharArray()[0]); }
                            else if (newInOrdLeft.length() != 0) { tempTree.left = work(preOrd, preOrdPoint+1, newInOrdLeft); }
                    catch (NoSuchElementException e) {}
                    try
                            String newInOrdRight = tok.nextToken();
                            if (newInOrdRight.length() == 1) { tempTree.right = new BinaryNode(newInOrdRight.toCharArray()[0]); }
                            else if (newInOrdRight.length() != 0) { tempTree.right = work(preOrd, preOrdPoint+1, newInOrdRight); }
                    catch (NoSuchElementException e) {}
                    return tempTree;
    class BinaryNode
            char chr;
            BinaryNode left = null;
            BinaryNode right = null;
            BinaryNode()
            BinaryNode(char c)
                    this(c, null, null);
            BinaryNode(char c, BinaryNode lt, BinaryNode rt)
                    chr = c;
                    left = lt;
                    right = rt;
            static int size(BinaryNode t)
                    if (t == null) { return 0; }
                    else { return size(t.left) + 1 + size(t.right); }
            static int height(BinaryNode t)
                    if (t == null) { return 0; }
                    else { return 1 + Math.max(BinaryNode.height(t.left), BinaryNode.height(t.right)); }
            void printPostOrder () {
                    if( left != null )
                            left.printPostOrder( ); // Left
                    if( right != null )
                            right.printPostOrder( ); // Right
                    System.out.print(chr); // Node
            static BinaryNode insert (char c, BinaryNode t)
                    Character tmp = new Character(c);
                    if (t == null)
                            t = new BinaryNode(c, null, null);
                    else if (tmp.compareTo(new Character(t.chr)) < 0)
                            t.left = insert(c, t.left );
                    else if (tmp.compareTo(new Character(t.chr)) > 0)
                            t.right = insert(c, t.right);
                    return t;
    }

    I don't know if this is a translation of your C code, but it can reconstruct any binary tree (with letters as nodes and no duplicates) from preorder and inorder traversals. Hope it helps.
    import java.util.*;
    public class ReconstructTree {
        public ReconstructTree() {
        public static void main(String[] args)
            String preorder = "ABDGKLRVWSXCEHMNFIOTUJPYQZ";
            String inorder = "KGVRWLSXDBAMHNECTOUIFPYJZQ";
            Map table = new HashMap();
            Map table2 = new HashMap();
            for(int i=0; i<inorder.length(); i++)
                table.put("" + inorder.charAt(i), new Integer(i));
                table2.put(new Integer(i), "" + inorder.charAt(i));
            List temppreorder = new ArrayList();
            for(int i=0; i<preorder.length(); i++)
                temppreorder.add(table.get("" + preorder.charAt(i)));
            Node root = constructTree(temppreorder);
            printPostOrder(root, table2);
        public static void printPostOrder(Node root, Map table)
            if(root == null)
                return;
            Node left = root.getLeft();
            Node right = root.getRight();
            printPostOrder(left, table);
            printPostOrder(right, table);
            System.out.print(table.get(new Integer(Integer.parseInt("" + root.getValue()))));
        public static Node constructTree(List preorder)
            Iterator it = preorder.iterator();
            int r = ((Integer)it.next()).intValue();
            Node root = new Node(r);
            Node node = root;
            while(it.hasNext())
                node = root;
                int a = ((Integer)it.next()).intValue();
                while(true)
                    r = node.getValue();
                    if(a < r)
                        if(node.getLeft() == null)
                            node.setLeft(new Node(a));
                            break;
                        else
                            node = node.getLeft();
                    else
                        if(node.getRight() == null)
                            node.setRight(new Node(a));
                            break;
                        else
                            node = node.getRight();
            return root;
        public static class Node
            private Node left = null;
            private Node right = null;
            private int value;
            public Node(int v)
                value = v;
            public int getValue()
                return value;
            public Node getLeft()
                return left;
            public Node getRight()
                return right;
            public void setLeft(Node l)
                left = l;
            public void setRight(Node r)
                right = r;
    }

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

  • 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