Advertisement
tanglinghui

printAllPaths

Jun 22nd, 2012
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. /**
  2.      * print all paths from root to leaf node
  3.      * using a helper function
  4.      * path is an array to store current nodes on the path
  5.      */
  6.     public void printAllPaths(){
  7.         TreeNode[] path = new TreeNode[100];
  8.         printAllPathHelper(root, path, 0);
  9.     }
  10.    
  11.     private void printAllPathHelper(TreeNode n,TreeNode[] path, int length){
  12.         if(n == null){
  13.             return;
  14.         }
  15.         path[length] = n;
  16.         length++;
  17.         //reached to the leaf node
  18.         if(n.leftChild==null&&n.rightChild==null){
  19.             printPath(path,length);
  20.         }else{
  21.             printAllPathHelper(n.leftChild, path, length);
  22.             printAllPathHelper(n.rightChild, path, length);
  23.         }
  24.     }
  25.    
  26.     private void printPath(TreeNode []path,int length){
  27.         int i = 0;
  28.         while(i<length){
  29.             System.out.print(path[i].data+" ");
  30.             i++;
  31.         }
  32.         System.out.println();
  33.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement