Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * print all paths from root to leaf node
- * using a helper function
- * path is an array to store current nodes on the path
- */
- public void printAllPaths(){
- TreeNode[] path = new TreeNode[100];
- printAllPathHelper(root, path, 0);
- }
- private void printAllPathHelper(TreeNode n,TreeNode[] path, int length){
- if(n == null){
- return;
- }
- path[length] = n;
- length++;
- //reached to the leaf node
- if(n.leftChild==null&&n.rightChild==null){
- printPath(path,length);
- }else{
- printAllPathHelper(n.leftChild, path, length);
- printAllPathHelper(n.rightChild, path, length);
- }
- }
- private void printPath(TreeNode []path,int length){
- int i = 0;
- while(i<length){
- System.out.print(path[i].data+" ");
- i++;
- }
- System.out.println();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement