Sara
Sara

Reputation: 37

traversal method with a return value

for trees, in traversal methods I want the values to be returned. the method i tried only returns one value.

 int inorder(BSTNode r) {
   int result = 0 ;
    if (r != null) {
        inorder(r.getLeft());
     result= r.getData();
        inorder(r.getRight());  
    }
   return result;
}

this code works perfectly but I want the method to return the values instead

private void inorder(BSTNode r) {
    if (r != null) {
        inorder(r.getLeft());
        System.out.print(r.getData() + " ");
        inorder(r.getRight());
    }
}

Upvotes: 3

Views: 2579

Answers (1)

snowp
snowp

Reputation: 66

You want to use some kind of list structure to accumulate the data:

void inorder(BSTNode r, List list) {
  if (r != null) {
    inorder(r.getLeft(), list);
    list.add(r.getData());
    inorder(r.getRight(), list);
  }
}

Invoking the function with

List list = new List();
inorder(bst, list);

After inorder completes, list will contain the the values of the tree.

The exact syntax would depend on the language you're using.

Upvotes: 3

Related Questions