For questions 1-3, you may assume that the following class structure exists. cla
ID: 3700671 • Letter: F
Question
For questions 1-3, you may assume that the following class structure exists.
class TreeNode {
int nodeData;
TreeNode left;
TreeNode right;
}
1.Define a recursive method that searches through a Tree and prints each element using an inorder traversal.
2. Define a recursive method that searches through a Tree and prints each element using an preorder traversal.
3. Define a recursive method that searches through a Tree and prints each element using an postorder traversal.
[The answers must be clear.]
Explanation / Answer
class TreeNode { int nodeData; TreeNode left; TreeNode right; } void printInorder(TreeNode root) { if(root != null) { printInorder(root.left); System.out.print(root.nodeData + " "); // in inorder data is print in the middle printInorder(root.right); } } void printPreorder(TreeNode root) { if(root != null) { System.out.print(root.nodeData + " "); // in preorder data is print before left and right trees printPreorder(root.left); printPreorder(root.right); } } void printPostorder(TreeNode root) { if(root != null) { printPostorder(root.left); printPostorder(root.right); System.out.print(root.nodeData + " "); // in postorder data is print after left and right trees } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.