2014-03-06 40 views
0

我在写这将在一定范围内存储的所有按键作为一个字符串函数BST:在递归函数的结果存储/ BST

String rangeToString(TreeNode root,int low, int high, String result){ 
    if(root==null) return ""; 
    if(root.key>low)) rangeToString(root.leftChild, low, high,result); 
    if(root.key>=low && root.key.<=high) result+=root.key; 
    if(root.key<high) rangeToString(root.rightChild,low,high,result); 
    return result; 

}

我基本上做的在遍历中,当它们在范围内时向字符串添加值。 目前它返回一个只包含根密钥的字符串。 我知道这个问题是在我的return语句,但我似乎无法得到如何实现功能没有他们。 任何人都可以指向正确的方向吗?

回答

0

首先,你可能要包括你的递归调用返回,因为你正在返回你的递归的结果:

String rangeToString(TreeNode root,int low, int high, String result){ 
    if(root==null) return ""; 
    if(root.key>low)) return rangeToString(root.leftChild, low, high,result); 
    if(root.key>=low && root.key.<=high) result+=root.key; 
    if(root.key<high) return rangeToString(root.rightChild,low,high,result); 
    return result; 
} 

我怀疑你的条件,所以我会花一些时间研究这些......事实上,递归的回报正在假设你的条件结构。

而且,聚会参数一个方式是很直观的方法是使用尾递归和您的参数积累的结果。

你可以在这里阅读更多: http://en.wikipedia.org/wiki/Tail_call

的关键是,您使用的参数本身聚集的结果,而当你的函数完成后,你回到你的参数(即累积的结果的那些) 。

0

你可以传递到你的参数的supplentary“积累到现在”的字符串列表(说你的名字curlist)。那么当你返回你回到这个curlist argument + .Add(your found key for this recursion level),并在地方,你递归调用fonction(rangeToString)您连接结果到当前列表curlist(使用追加或其他)。

伪代码:

list<string> myRecursiveFunc(some args, list<string> curlist) 
{ 
    if (recursConditionOK) 
     curlist = curlist.Append(myRecusriveFunc, curlist); 
    return curlist; 
}