For example, the output for the below tree should be: 4 5 6 7 2 3 1
public class PrintDataInReverseOrder {
public static void main(String args[]) {
Node rootNode = new Node("1");
rootNode.left = new Node("2");
rootNode.left.left = new Node("4");
rootNode.left.right = new Node("5");
rootNode.right = new Node("3");
rootNode.right.right = new Node("7");
rootNode.right.left = new Node("6");
printInreverse(rootNode);
}
static void printInreverse(Node node) {
Queue<Node> queue = new LinkedBlockingQueue<>();
queue.add(node);
Stack<String> stack = new Stack<>();
while(!queue.isEmpty()) {
Node node1 = queue.remove();
stack.add(node1.value);
if(null!=node1.right) {
queue.add(node1.right);
}
if(null!=node1.left) {
queue.add(node1.left);
}
}
while(!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
class BinayTree{
static class Node{
String value;
Node left;
Node right;
Node(String val){
value = val;
left = right = null;
}
}
}
output: 4567231
public class PrintDataInReverseOrder {
public static void main(String args[]) {
Node rootNode = new Node("1");
rootNode.left = new Node("2");
rootNode.left.left = new Node("4");
rootNode.left.right = new Node("5");
rootNode.right = new Node("3");
rootNode.right.right = new Node("7");
rootNode.right.left = new Node("6");
printInreverse(rootNode);
}
static void printInreverse(Node node) {
Queue<Node> queue = new LinkedBlockingQueue<>();
queue.add(node);
Stack<String> stack = new Stack<>();
while(!queue.isEmpty()) {
Node node1 = queue.remove();
stack.add(node1.value);
if(null!=node1.right) {
queue.add(node1.right);
}
if(null!=node1.left) {
queue.add(node1.left);
}
}
while(!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
class BinayTree{
static class Node{
String value;
Node left;
Node right;
Node(String val){
value = val;
left = right = null;
}
}
}
output: 4567231