-1

I'm trying to print the path from the root to a specified node. But the issue here that I have to use the node in the parameter, as: public ArrayList> pathOf(TreeNode x)

I've tried this:

public java.util.ArrayList<TreeNode<E>> pathOf(TreeNode<E> x) {
    ArrayList<TreeNode<E>> list = new ArrayList<TreeNode<E>>();
    TreeNode<E> current = root; // Start from the root

    while (current != null) {
        list.add(current); // Add the node to the list
        if (x.element.compareTo(current.element) < 0) {
            current = current.left;
        } else if (x.element.compareTo(current.element) > 0) {
            current = current.right;
        } else {
            break;
        }
    }

    return list; // Return an array of nodes
}

When I'm calling the method: System.out.println("path of : " + tree.pathOf(66));

I'm getting this message: incompatible types: int cannot be converted to TreeNode

Thank you in advance

Roy
  • 39
  • 4

1 Answers1

2

When you call pathOf(TreeNode<E> x) it expects a TreeNode variable. Simply do something like pathOf(new TreeNode<Integer>(arg1, arg2, ...)) // Replace arg# with suitable arguments

In other words, don't call pathOf(66), call pathOf(someTreeNodeVariable)

Note: If you want to print custom objects, How do I print my Java object without getting "SomeType@2f92e0f4"? will be very helpful to you.

FailingCoder
  • 757
  • 1
  • 8
  • 20
  • I've tried it, it shows: path of : [TreePractice.TreeNode@15db9742, TreePractice.TreeNode@6d06d69c, TreePractice.TreeNode@7852e922, TreePractice.TreeNode@4e25154f] – Roy Oct 17 '19 at 02:29
  • https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4 – FailingCoder Oct 17 '19 at 02:30