1

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());
    }
}
4

1 回答 1

2

您想使用某种列表结构来累积数据:

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

调用函数

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

inorder 完成后,list将包含树的值。

确切的语法取决于您使用的语言。

于 2015-05-08T17:50:40.657 回答