8.5k views
3 votes
Specify the correct implementation of in-order traverse algorithm for binary trees. Select one: void inOrder(Node p) { if (p != null) { visit(p); inOrder(p.left); inOrder(p.right); } } void inOrder(Node p) { inOrder(p.left); visit(p); inOrder(p.right); } void inOrder(Node p) { if (p != null) { inOrder(p.left); visit(p); inOrder(p.right); } } void inOrder(Node p) { if (p == null) { inOrder(p.left); visit(p); inOrder(p.right); } }

1 Answer

4 votes

Final answer:

The correct in-order traversal method first checks if the current node is not null, traverses the left subtree, visits the current node, and then traverses the right subtree.

Step-by-step explanation:

The correct implementation of the in-order traverse algorithm for binary trees is the one where the function visits the left subtree, then the current node, and finally the right subtree. The right implementation is:

void inOrder(Node p) {
if (p != null) {
inOrder(p.left);
visit(p);
inOrder(p.right);
}}

It's important to check whether the current node is not null before making recursive calls, to ensure that the base case for the recursive calls is established. This prevents the algorithm from calling methods on null objects, which would cause a NullPointerException.

User Jeff Jirsa
by
7.8k points