Skip to content

Instantly share code, notes, and snippets.

@rishabh1403
Created July 30, 2016 08:04
Show Gist options
  • Save rishabh1403/4ad2a5d33cf45bf55156309087382538 to your computer and use it in GitHub Desktop.
Save rishabh1403/4ad2a5d33cf45bf55156309087382538 to your computer and use it in GitHub Desktop.
Recursive and iterative Pre-order traversal of a BinaryTree
//TODO add morrisTraversal
import java.util.*;
//Node class
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
this.left=null;
this.right = null;
}
}
public class PreOrder {
public static void main(String args[]){
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
//root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
iterativePreOrder(root);
System.out.println();
recursivePreOrder(root);
}
// recursive method
private static void recursivePreOrder(Node root) {
// TODO Auto-generated method stub
if(root != null){
System.out.print(root.data+" ");
recursivePreOrder(root.left);
recursivePreOrder(root.right);
}
//System.out.println();
}
// iterative method
private static void iterativePreOrder(Node root) {
// TODO Auto-generated method stub
if(root == null)
return;
Stack<Node> s = new Stack<Node>();
s.push(root);
while(!s.isEmpty()){
Node t = s.pop();
System.out.print(t.data+" ");
if(t.right!=null)s.push(t.right);
if(t.left!=null)s.push(t.left);
}
}
}
@rishabh1403
Copy link
Author

add morris traversal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment