Question

Write a public method “printRootToLeafPath()” that prints out ALL its root-to-leaf paths. Note: you should use...

Write a public method “printRootToLeafPath()” that prints out ALL its root-to-leaf paths. Note: you should use internal recursive private method to print all paths

java code

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Node.Java

class Node

{

int num;

Node leftNode,rightNode;

Node(int element)

{

num=element;

leftNode=rightNode=null;

}

}

Main.java

class Main

{

Node rootNode;

public static void printRootToLeafPath(Node node)

{

int p[]=new int[100];

printRootToLeafPathRecursive(node,p,0);

}

public static void printRootToLeafPathRecursive(Node n, int p[], int len){

if(n== null)

return;

p[len]=n.num;

len++;

if(n.leftNode==null && n.rightNode==null)

displayArr(p,len);

else

{

printRootToLeafPathRecursive(n.leftNode,p,len);

printRootToLeafPathRecursive(n.rightNode,p,len);

}

}

public static void displayArr(int nums[],int len)

{

for (int i=0;i<len;i++)

{

System.out.print(nums[i]+" ");

}

System.out.println("");

}

public static void main(String args[])

{

Main BTree=new Main();

BTree.rootNode=new Node(15);

BTree.rootNode.leftNode=new Node(9);

BTree.rootNode.rightNode=new Node(1);

BTree.rootNode.leftNode.leftNode=new Node(4);

BTree.rootNode.leftNode.rightNode=new Node(6);

BTree.rootNode.rightNode.leftNode=new Node(3);

BTree.printRootToLeafPath(BTree.rootNode);

}

}

if you like the answer please provide a thumbs up.

Add a comment
Know the answer?
Add Answer to:
Write a public method “printRootToLeafPath()” that prints out ALL its root-to-leaf paths. Note: you should use...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT