Package problems.geeks.tree

Source Code of problems.geeks.tree.Q056_Reverse_Level_Order_Traversal

package problems.geeks.tree;

/**
* Reverse Level Order Traversal
*
* http://www.geeksforgeeks.org/reverse-level-order-traversal/
*
* We have discussed level order traversal of a post in previous post. The idea is to print last level first, then second last level, and so on.
* Like Level order traversal, every level is printed from left to right.
*
*           1
*         /   \
*        2     3
*       / \   / \
*      4   5 6   7
*     
* Reverse Level order traversal of the above tree is "4 5 6 7 2 3 1".
*/

import java.util.*;
import adt.tree.Tree;
import adt.tree.TreeNode;

public class Q056_Reverse_Level_Order_Traversal {

  public static void main(String[] args) {
    TreeNode root = Tree.tree1();
    reverseLevelOrder(root);
  }
 
  static void reverseLevelOrder(TreeNode root) {
    if (root == null) {
      return;
    }
   
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
   
    Stack<Integer> stack = new Stack<Integer>();
   
    while (!queue.isEmpty()) {
      TreeNode node = queue.poll();
      stack.push(node.val);
     
      if (node.right != null) {
        queue.add(node.right);
      }
     
      if (node.left != null) {
        queue.add(node.left);
      }
    }
   
    while (!stack.isEmpty()) {
      System.out.format("%d ", stack.pop());
    }
  }
 
}
TOP

Related Classes of problems.geeks.tree.Q056_Reverse_Level_Order_Traversal

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.