【发布时间】:2011-12-25 18:42:34
【问题描述】:
我在 C++ 中为我的一项任务实现了一个基于链接的 BST(二叉搜索树)。我已经编写了整个班级并且一切正常,但我的作业要求我绘制以下运行时间:
a. A sorted list of 50000, 75000, and 100000 items
b. A random list of 50000, 75000, and 100000 items
没关系,我可以插入数字,但它也要求我调用树上的 FindHeight() 和 CountLeaves() 方法。我的问题是我已经使用recursion 实现了这两个功能。由于我有一个如此大的数字列表,我得到了一个stackoverflow 异常。
这是我的类定义:
template <class TItem>
class BinarySearchTree
{
public:
struct BinarySearchTreeNode
{
public:
TItem Data;
BinarySearchTreeNode* LeftChild;
BinarySearchTreeNode* RightChild;
};
BinarySearchTreeNode* RootNode;
BinarySearchTree();
~BinarySearchTree();
void InsertItem(TItem);
void PrintTree();
void PrintTree(BinarySearchTreeNode*);
void DeleteTree();
void DeleteTree(BinarySearchTreeNode*&);
int CountLeaves();
int CountLeaves(BinarySearchTreeNode*);
int FindHeight();
int FindHeight(BinarySearchTreeNode*);
int SingleParents();
int SingleParents(BinarySearchTreeNode*);
TItem FindMin();
TItem FindMin(BinarySearchTreeNode*);
TItem FindMax();
TItem FindMax(BinarySearchTreeNode*);
};
FindHeight() 实现
template <class TItem>
int BinarySearchTree<TItem>::FindHeight()
{
return FindHeight(RootNode);
}
template <class TItem>
int BinarySearchTree<TItem>::FindHeight(BinarySearchTreeNode* Node)
{
if(Node == NULL)
return 0;
return 1 + max(FindHeight(Node->LeftChild), FindHeight(Node->RightChild));
}
CountLeaves() 实现
template <class TItem>
int BinarySearchTree<TItem>::CountLeaves()
{
return CountLeaves(RootNode);
}
template <class TItem>
int BinarySearchTree<TItem>::CountLeaves(BinarySearchTreeNode* Node)
{
if(Node == NULL)
return 0;
else if(Node->LeftChild == NULL && Node->RightChild == NULL)
return 1;
else
return CountLeaves(Node->LeftChild) + CountLeaves(Node->RightChild);
}
我试图考虑如何在不递归的情况下实现这两种方法,但我完全被难住了。有人有什么想法吗?
【问题讨论】:
-
(a) 问题标题应该描述问题,而不是你的情绪状态/希望&梦想; (b) 我们不在乎您的任务何时到期!; (c) 无需在帖子上签名。祝你好运!
-
@SaadImran:可以肯定地说插入没有任何平衡吗?
-
@SaadImran:一时兴起,如果您在发布版本中使用
BinarySearchTreeNode*的函数原型之前加上static这个词,它仍然会溢出吗?例如:static void PrintTree(BinarySearchTreeNode*); -
@MooingDuck 是的,你是对的,我并没有真正考虑足够远来平衡树,我只是将数字 1-100,000 插入到树中。我将尝试平衡以及添加 static 关键字。谢谢!
-
研究使用红黑语义进行平衡。使用适当平衡的树,您只需执行
ceil(lg n)级别的递归。即使函数是非静态的,也不应该用完堆栈空间。
标签: c++ recursion stack-overflow binary-search-tree