print a binary tree level wise from leaves to root

Write an algorithm to print a binary tree level wise and that too from leaves to root. Also only one queue and one stack can be used for the purpose.

Comments

  1. public void print_leaf_to_root(Node root){
    QueueDemo qd = new QueueDemo();
    Queue queue = qd.create_queue(); /* returns Queue*/
    Stack s = new Stack();
    qd.enqueue(queue, root);
    s.push(root.value);
    while(!qd.isempty(queue)){
    Node root_1 = qd.dequeue(queue);
    if(root_1.right!=null){
    qd.enqueue(queue, root_1.right);
    }
    if(root_1.right!=null){
    s.push(root_1.right.value);
    }
    if(root_1.left!=null){
    qd.enqueue(queue, root_1.left);
    }
    if(root_1.left!=null){
    s.push(root_1.left.value);
    }
    }
    while(!s.isEmpty()){
    System.out.println(s.pop());
    }

    }

    ReplyDelete

Post a Comment

Popular posts from this blog