-1

I have a BinaryTree class which contains Root node of custom type TreeNode.

TreeNode class has,

T value;  
BTree<T> left, right; 

BTree is an interface which is implemented in BinaryTree. in that binary tree class there is a method to check whether the tree contains specific value in a node.

@Override
public boolean contains(T value) {
    return false;
}

I need to implement this method, maybe i have to use a recursive way.

Scoopa
  • 45
  • 12

1 Answers1

0

Yes, you need to recursively search the tree. Code will look something like this:

public boolean contains(BTree<T> root, T value) {
    if (root == null) {
        return false;
    }
    if (root.getValue().equals(value)) {
        return true;
    }

    return contains(root.getLeft(), value) || contains(root.getRight(), value);
}

@Override
public boolean contains(T value) {
    return contains(this, value);
}
Kaidul
  • 15,409
  • 15
  • 81
  • 150