0

I am having trouble finding the smallest element of a binary search tree. I have some code finished, but it is not working.

public T getMinElement(TreeNode<T> node) {
    //TODO: implement this
    if (node == null){
        return null;
    }
     if (node.getLeftChild() == null){
        return (T) node;
     }
     else{
        return getMinElement(node);
  }
}
1
  • 2
    What do you mean by "it is not working"? Please provide more details about the problem you have encountered. Commented Dec 7, 2012 at 1:51

1 Answer 1

6

You were almost there! You just need to recurse on the left child of your binary search tree (always guaranteed to be smaller). Also you had some syntax errors, which I fixed.

public <T> T getMinElement(TreeNode<T> node) {
  if (node == null){
    return null;
  }
  if (node.getLeftChild() == null){
    return node.getData(); // or whatever your method is
  } else{
    return getMinElement(node.getLeftChild());
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.