Created
July 30, 2016 08:04
-
-
Save rishabh1403/4ad2a5d33cf45bf55156309087382538 to your computer and use it in GitHub Desktop.
Recursive and iterative Pre-order traversal of a BinaryTree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
add morris traversal