Package problems.geeks.tree

Source Code of problems.geeks.tree.Q001_Tree_Traversals

package problems.geeks.tree;

/**
* Tree Traversals
*
* http://www.geeksforgeeks.org/618/
*
* Inorder Traversal:
*
* Algorithm Inorder(tree)
*    1. Traverse the left subtree, i.e., call Inorder(left-subtree)
*    2. Visit the root.
*    3. Traverse the right subtree, i.e., call Inorder(right-subtree)
* Uses of Inorder
* In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order.
* To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder itraversal s reversed, can be used.
* Example: Inorder traversal for the above given figure is 4 2 5 1 3.
*
* Preorder Traversal:
*
* Algorithm Preorder(tree)
*    1. Visit the root.
*    2. Traverse the left subtree, i.e., call Preorder(left-subtree)
*    3. Traverse the right subtree, i.e., call Preorder(right-subtree)
* Uses of Preorder
* Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on of an expression tree.
* Please see http://en.wikipedia.org/wiki/Polish_notation to know why prefix expressions are useful.
* Example: Preorder traversal for the above given figure is 1 2 4 5 3.
*
* Postorder Traversal:
*
* Algorithm Postorder(tree)
*    1. Traverse the left subtree, i.e., call Postorder(left-subtree)
*    2. Traverse the right subtree, i.e., call Postorder(right-subtree)
*    3. Visit the root.
* Uses of Postorder
* Postorder traversal is used to delete the tree. Please see the question for deletion of tree for details.
* Postorder traversal is also useful to get the postfix expression of an expression tree.
* Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation to for the usage of postfix expression.
*
* Levelorder Traversal:
*
* METHOD 1 (Use function to print a given level)
*
* Algorithm:
* There are basically two functions in this method. One is to print all nodes at a given level (printGivenLevel), and other is to print level order traversal of the tree (printLevelorder). printLevelorder makes use of printGivenLevel to print nodes at all levels one by one starting from root.
*
* Function to print level order traversal of tree
* printLevelorder(tree)
* for d = 1 to height(tree)
*    printGivenLevel(tree, d);
*
* Function to print all nodes at a given level
* printGivenLevel(tree, level)
* if tree is NULL then return;
* if level is 1, then
*     print(tree->data);
* else if level greater than 1, then
*     printGivenLevel(tree->left, level-1);
*     printGivenLevel(tree->right, level-1);
*    
* METHOD 2 (Use Queue)
*
* Algorithm:
* For each node, first the node is visited and then it�s child nodes are put in a FIFO queue.
*
* printLevelorder(tree)
* 1) Create an empty queue q
* 2) temp_node = root (start from root)
* 3) Loop while temp_node is not NULL
*     a) print temp_node->data.
*     b) Enqueue temp_node�s children (first left then right children) to q
*     c) Dequeue a node from q and assign it�s value to temp_node
*
* Example:
*               1
*             /   \
*           2      3
*          / \    / \
*         4   5  6   7
*/

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

public class Q001_Tree_Traversals {
 
  public static void main(String[] args) {
    TreeNode root = Tree.tree1();
   
    System.out.format("Preorder\n");
    preorder(root);
    System.out.format("\n");
    preorderR(root);
    System.out.format("\n\n");
   
    System.out.format("Inorder\n");
    inorder(root);
    System.out.format("\n");
    inorderR(root);
    System.out.format("\n\n");
   
    System.out.format("Postorder\n");
    postorder(root);
    System.out.format("\n");
    postorderR(root);
    System.out.format("\n\n");
   
    System.out.format("Levelorder\n");
    levelorder(root);
    System.out.format("\n");
    levelorderR(root);
    System.out.format("\n\n");
  }
 
  // -------------------------
  //  Pre-order Recursion
  //
  //  1 2 4 5 3 6 7
  // -------------------------
  static void preorderR(TreeNode root) {
    if (root == null) {
      return;
    }
   
    System.out.format("%d ", root.val);
    preorderR(root.left);
    preorderR(root.right);
  }
 
  // -------------------------
  //  Pre-order Iterative
  //
  //  1 2 4 5 3 6 7
  // -------------------------
  static void preorder(TreeNode root) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode curr = root;
   
    while (!stack.isEmpty() || curr != null) {
      if (curr != null) {
        System.out.format("%d ", curr.val);
        stack.push(curr);
        curr = curr.left;
      } else {
        curr = stack.pop();
        curr = curr.right;
      }
    }
  }
 
  // -------------------------
  //  In-order Recursion
  //
  //  4 2 5 1 6 3 7
  // -------------------------
  static void inorderR(TreeNode root) {
    if (root == null) {
      return;
    }
   
    inorderR(root.left);
    System.out.format("%d ", root.val);
    inorderR(root.right);
  }
 
  // -------------------------
  //  In-order Iterative
  //
  //  4 2 5 1 6 3 7
  // -------------------------
  static void inorder(TreeNode root) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode curr = root;
   
    while (!stack.isEmpty() || curr != null) {
      if (curr != null) {
        stack.push(curr);
        curr = curr.left;
      } else {
        curr = stack.pop();
        System.out.format("%d ", curr.val);
        curr = curr.right;
      }
    }
  }
 
  // -------------------------
  // Inorder Tree Traversal without recursion and without stack
  //
  // Using Morris Traversal, we can traverse the tree without using stack and recursion.
  // The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal,
  // we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree.
  //
  // 1. Initialize current as root
  // 2. While current is not NULL
  //    If current does not have left child
  //       a) Print current�s data
  //       b) Go to the right, i.e., current = current->right
  //    Else
  //       a) Make current as right child of the rightmost node in current's left subtree
  //       b) Go to this left child, i.e., current = current->left
  //
  // Although the tree is modified through the traversal, it is reverted back to its original shape after the completion.
  // Unlike Stack based traversal, no extra space is required for this traversal.
  // -------------------------
 
 
 
  // -------------------------
  //  Post-order Recursion
  //
  //  4 5 2 6 7 3 1
  // -------------------------
  static void postorderR(TreeNode root) {
    if (root == null) {
      return;
    }
   
    postorderR(root.left);
    postorderR(root.right);
    System.out.format("%d ", root.val);
  }
 
  // -------------------------
  //  Post-order Iterative
  // -------------------------
  static void postorder(TreeNode root) {
    if (root == null) {
      return;
    }
   
    Stack<TreeNode> in_stack = new Stack<TreeNode>();
    Stack<TreeNode> out_stack = new Stack<TreeNode>();
   
    in_stack.push(root);
   
    while (!in_stack.isEmpty()) {
      TreeNode node = in_stack.pop();
      out_stack.push(node);
     
      if (node.left != null) {
        in_stack.push(node.left);
      }
     
      if (node.right != null) {
        in_stack.push(node.right);
      }
    }
   
    while (!out_stack.isEmpty()) {
      TreeNode node = out_stack.pop();
      System.out.format("%d ", node.val);
    }
  }
 
  // -------------------------
  //  Level-order Recursion
  // -------------------------
  static void levelorderR(TreeNode root) {
    int n = root.getHeight();
    for (int i = 1; i <= n; i++) {
      printLevel(root, i);
    }
  }
 
  static void printLevel(TreeNode root, int level) {
    if (root == null) {
      return;
    }
   
    if (level == 1) {
      System.out.format("%d ", root.val);
      return;
    }
   
    printLevel(root.left, level - 1);
    printLevel(root.right, level - 1);
  }
 
  // -------------------------
  //  Level-order Iterative
  // -------------------------
  static void levelorder(TreeNode root) {
    if (root == null) {
      return;
    }
   
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
   
    while (!queue.isEmpty()) {
      TreeNode node = queue.poll();
      System.out.format("%d ", node.val);
     
      if (node.left != null) {
        queue.add(node.left);
      }
     
      if (node.right != null) {
        queue.add(node.right);
      }
    }
  }

}
TOP

Related Classes of problems.geeks.tree.Q001_Tree_Traversals

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.