Write a program for recursive Traverse

Showing Answers 1 - 2 of 2 Answers

Code
  1.  public void preorder( ) {

  2.     if( root == null ) return;

  3.  

  4.     Stack<Node> stack = new Stack<Node>( );

  5.     stack.push( root );

  6.  

  7.     while( ! stack.isEmpty( ) ) {

  8.         Node current = stack.pop( );

  9.         if( current.right != null ) stack.push( current.right );

  10.         if( current.left != null ) stack.push( current.left );

  11.         System.out.print( current.data + " " );

  12.     }

  13. }

  14.  

  15. /** Iteratively traverses the binary tree in in-order */

  16. public void inorder( ) {

  17.     Node node = root;

  18.     Stack<Node> stack = new Stack<Node>( );

  19.     while( ! stack.isEmpty( ) || node != null ) {

  20.         if( node != null ) {

  21.             stack.push( node );

  22.             node = node.left;

  23.         } else {

  24.             node = stack.pop( );

  25.             System.out.print( node.data + " " );

  26.             node = node.right;

  27.         }

  28.     }

  29. }

  30.  

  31. /** Iteratively traverses the binary tree in post-order */

  32. public void postorder( ) {

  33.     if( root == null ) return;

  34.  

  35.     Stack<Node> stack = new Stack<Node>( );

  36.     Node current = root;

  37.  

  38.     while( true ) {

  39.  

  40.         if( current != null ) {

  41.             if( current.right != null ) stack.push( current.right );

  42.             stack.push( current );

  43.             current = current.left;

  44.             continue;

  45.         }

  46.  

  47.         if( stack.isEmpty( ) ) return;

  48.         current = stack.pop( );

  49.  

  50.         if( current.right != null && ! stack.isEmpty( ) && current.right == stack.peek( ) ) {

  51.             stack.pop( );

  52.             stack.push( current );

  53.             current = current.right;

  54.         } else {

  55.             System.out.print( current.data + " " );

  56.             current = null;

  57.         }

  58.     }

  59. }


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions