Friday, November 8, 2019

How To Implement Binary Tree Preorder Traversal Inwards Coffee Without Recursion - Iterative Example

This is my minute article on how to implement binary tree pre-order traversal inwards Java. In the first part, I convey shown how to traverse a binary tree alongside a pre-order traversal algorithm using Recursion, as well as inwards this article, you lot volition larn how to implement pre-order traversal without using Recursion. You mightiness last thinking that why practise you lot demand to larn the iterative solution if a recursive solution is possible as well as slow to write? Well, this type of inquiry is generally asked on Programming Job interviews as well as Interviewers similar to reckon how comfortable a candidate is alongside both Recursion equally good equally using other data structures as well as iteration.

Apart from that, Iterative solution is too ofttimes preferred inwards existent code because Recursive solution tin strength out e'er come across StackOverflow mistake when a release of nodes increase as well as Recursion gets deeper as well as deeper.  That's why an iterative solution is considered condom as well as if possible you lot should e'er purpose that for your production code.

Just to revise, pre-order is a depth-first algorithm, where the depth of the tree is start explored earlier traversing sibling. In preOrder traversal, first, node or beginning is visited, so left subtree, as well as correct subtree, thus it is too known equally NLR (Node-Left-Right) algorithm.

You mightiness know that when you lot purpose Recursion, methods calls are stored inwards an internal Stack which unwinds itself when the algorithm reaches the base of operations case.

When recursion is non allowed, you lot tin strength out purpose the Stack information construction to practise the same effect, inwards fact, this is too a mutual technique to convert a recursive algorithm into an iterative one.

Btw, if you lot are non familiar alongside essential information construction similar Stack, Queue, Array, LinkedList, Binary tree as well as Hash tabular array then  I propose you lot bring together a goodness course of pedagogy like Data Structures as well as Algorithms: Deep Dive Using Java on Udemy, it's ane of the best course of pedagogy to larn as well as master copy information construction as well as Algorithms. Even if you lot know information structure, this tin strength out last used to farther strengthen your knowledge.




Pre-order traversal inwards Java without recursion

There is no doubtfulness that the recursive algorithm of pre-order traversal was readable, clear, as well as concise. You should e'er prefer such algorithm over iterative one, only if you lot convey been asked to solve this occupation without recursion so you lot convey no choice. In gild to convert that recursive algorithm to an iterative one, you lot tin strength out purpose a Stack.

You start traversal yesteryear pushing the beginning node into Stack as well as loop until Stack is empty. In each iteration, you lot popular the final chemical factor from Stack as well as impress its value. That agency you lot visited it. Now, force the left as well as correct nodes into Stack if they are non null.

The gild on which you lot force the left as well as correct node is critical. You must start force correct subtree followed yesteryear left subtree because inwards pre-order nosotros see left subtree later the node.

In side yesteryear side iteration when you lot telephone phone pop() it volition provide left node because Stack is a LIFO information structure, to larn to a greater extent than virtually Stack, you lot tin strength out bring together a comprehensive course of pedagogy on information structures as well as algorithms like binary tree tutorial.

The BinaryTree shape is your binary tree as well as TreeNode is your private nodes inwards the tree. This time, though I convey moved the logic to practise a sample binary tree within the BinaryTree shape itself. This way, you lot don't demand to practise a novel tree every fourth dimension inwards the main() method.

Here is a diagram of the iterative pre-order traversal algorithm which volition brand the steps clearer:

Java, Python, as well as JavaScript



Iterative Pre-Order Traversal of Binary Tree inwards Java

import java.util.Stack;  /*  * Java Program to traverse a binary tree   * using PreOrder traversal without recursion.   * In PreOrder the node value is printed first,  * followed yesteryear see to left as well as correct subtree.  *   * input:  *     a  *    / \  *   b   e  *  / \   \  * c   d   f  *   * output: a b c d e f   */  public class Main {    public static void main(String[] args) throws Exception {      // build the binary tree given inwards question     BinaryTree bt = BinaryTree.create();      // traversing binary tree inwards PreOrder without using recursion     System.out         .println("printing nodes of a binary tree inwards preOrder using recursion");      bt.preOrderWithoutRecursion();    }  }  class BinaryTree {   static class TreeNode {     String data;     TreeNode left, right;      TreeNode(String value) {       this.data = value;       left = right = null;     }      boolean isLeaf() {       return left == null ? right == null : false;     }    }    // beginning of binary tree   TreeNode root;    /**    * Java method to see tree nodes inwards PreOrder traversal without recursion.    */   public void preOrderWithoutRecursion() {     Stack<TreeNode> nodes = new Stack<>();     nodes.push(root);      while (!nodes.isEmpty()) {       TreeNode electrical flow = nodes.pop();       System.out.printf("%s ", current.data);        if (current.right != null) {         nodes.push(current.right);       }       if (current.left != null) {         nodes.push(current.left);       }     }   }    /**    * Java method to practise binary tree alongside exam information    *     * @return a sample binary tree for testing    */   public static BinaryTree create() {     BinaryTree tree = new BinaryTree();     TreeNode beginning = new TreeNode("a");     tree.root = root;     tree.root.left = new TreeNode("b");     tree.root.left.left = new TreeNode("c");      tree.root.left.right = new TreeNode("d");     tree.root.right = new TreeNode("e");     tree.root.right.right = new TreeNode("f");      return tree;   }  }  Output printing nodes of a binary tree in preOrder using recursion a b c d e f 


That's all virtually how to traverse a binary tree using PreOrder traversal inwards Java. The gild inwards which you lot see the node left as well as correct subtree is fundamental because that gild determines your traversal algorithm. If you lot see the node start agency it preOrder, if you lot see the node minute agency its InOrder as well as when you lot see the node final so its called postOrder traversal.

Further Learning
Data Structures as well as Algorithms: Deep Dive Using Java
program)
  • How to implement in-order traversal inwards Java? (solution)
  • How to implement in-order traversal inwards Java without recursion? (solution)
  • How to implement pre-order traversal inwards Java?  (solution)
  • 5 Free Data Structure as well as Algorithms Courses for Programmers (courses)
  • 10 Algorithms Books Every Programmer Should read (books)
  • How to implement a linked listing using generics inwards Java? (solution)
  • How to traverse a binary tree inwards pre-order without using recursion? (solution)
  • 5 information construction as well as algorithm books for coding interviews (list)
  • How to impress duplicate elements of an array inwards Java? (solution)
  • How to contrary an array inwards house inwards Java? (solution)
  • How to contrary a singly linked listing inwards Java? (solution)
  • 50+ Data Structure as well as Algorithms Problems from Interviews (questions)
  • How to honour the middle chemical factor of the linked listing using a unmarried pass? (solution)
  • How to honour the tertiary chemical factor from the destination of a linked listing inwards Java? (solution)
  • 10 Free Data Structure as well as Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)

  • Thanks for reading this article so far. If you lot similar this Java Array tutorial so delight percentage alongside your friends as well as colleagues. If you lot convey whatsoever questions or feedback so delight driblet a comment.

    P. S. - If you lot are looking for closed to Free Algorithms courses to amend your agreement of Data Structure as well as Algorithms, so you lot should too banking concern jibe the Easy to Advanced Data Structures course of pedagogy on Udemy. It's authored yesteryear a Google Software Engineer as well as Algorithm proficient as well as its completely complimentary of cost.

    No comments:

    Post a Comment