我需要为跟随树接口
创建顺序遍历的递归函数// EFFECTS: returns true if tree is empty, false otherwise
bool tree_isEmpty (const tree_t& tree);
// EFFECTS: creates an empty tree.
tree_t tree_make ();
// EFFECTS: creates a new tree, with elt as it's element, left as
// its left subtree, and right as its right subtree
tree_t tree_make (int elt, const tree_t& left, const tree_t& right);
// REQUIRES: tree is not empty
// EFFECTS: returns the element at the top of tree.
int tree_elt (const tree_t& tree);
// REQUIRES: tree is not empty
// EFFECTS: returns the left subtree of tree
tree_t tree_left (const tree_t& tree);
// REQUIRES: tree is not empty
// EFFECTS: returns the right subtree of tree
tree_t tree_right (const tree_t& tree);
// MODIFIES: cout
// EFFECTS: prints tree to cout.
void tree_print (const tree_t& tree);
我不能用于,虽然或goto循环我尝试创建功能但不幸的是它不起作用请帮助。我的功能在下面
list_t traversal_helper(tree_t tree,list_t l){
if (tree.is_empty())
return l;
/* first recur on left child */
traversal_helper (tree.get_left_tree(),l);
/* then print the data of node */
l=list_make(tree.get_elt(),l);
/* now recur on right child */
traversal_helper (tree.get_right_tree(),l);
}
list_t traversal(tree_t tree){
list_t l=list_make();
if(tree.is_empty()){
return list_make();
}
else{
return traversal_helper(tree,l);
}
}
My list_t interface contain following functions:
List Interface
The file recursive.h defines the type "list_t" and the following operations on lists:
// EFFECTS: returns true if list is empty, false otherwise
bool list_isEmpty (const list_t& list);
// EFFECTS: returns an empty list.
list_t list_make ();
// EFFECTS: given the list (list) make a new list consisting of
// the new element followed by the elements of the
// original list.
list_t list_make (int elt, const list_t& list);
// REQUIRES: list is not empty
// EFFECTS: returns the first element of list
int list_first (const list_t& list);
// REQUIRES: list is not empty
// EFFECTS: returns the list containing all but the first element of list
list_t list_rest (const list_t& list);
// MODIFIES: cout
// EFFECTS: prints list to cout.
void list_print (const list_t& list);
答案 0 :(得分:1)
traversal_helper
永远不会返回任何内容,并且它不使用递归调用的返回值 - 我想你想要这样的东西:
list_t traversal_helper(tree_t tree,list_t l){
if (tree.is_empty())
return l;
/* first recur on left child */
l = traversal_helper (tree.get_left_tree(),l);
/* then print the data of node */
l=list_make(tree.get_elt(),l);
/* now recur on right child */
return traversal_helper (tree.get_right_tree(),l);
}
如果list_make
创建一个在列表末尾附加元素的新列表,这应该有用。如果它将元素附加在列表的开头,那么结果将需要反转。