Advertisement
Guest User

Binary Tree Traversals - Implementation in Java

a guest
Jul 3rd, 2011
716
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. void preorderT(Node root){
  2.     if (root==null) return;
  3.    
  4.     root.visit();
  5.     preorderT(root.left);
  6.     preorderT(root.right);
  7. }
  8.  
  9. void postorderT(Node root){
  10.     if (root==null) return;
  11.    
  12.     preorderT(root.left);
  13.     preorderT(root.right);
  14.     root.visit();  
  15. }
  16.  
  17. void inorderT(Node root){
  18.     if (root==null) return;
  19.    
  20.     preorderT(root.left);
  21.     root.visit();
  22.     preorderT(root.right);
  23. }
  24.  
  25. /* Non-Recursive Implementation of Preorder Traversal */
  26.  
  27. public class Stack{
  28.     public void push(Node node) {...}
  29.     public Node pop() {...}
  30.     public boolean isEmpty() {...}
  31. }
  32.  
  33. void preorderTNR(Node root){
  34.     Stack stack=new Stack();
  35.     stack.push(root);
  36.    
  37.     //Note that I had forgotten the () after isEmpty in the video
  38.     while(!stack.isEmpty()){
  39.         Node n=stack.pop();
  40.        
  41.         n.visit();
  42.         if (n.right!=null)stack.push(n.right);
  43.         if (n.left!=null)stack.push(n.left);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement