【发布时间】:2013-12-01 19:17:08
【问题描述】:
我在Tree 类中有一个计算二叉搜索树深度的方法。
我的额外任务是,在计算树的深度时,还存储(或以某种方式保留)这条路径上的节点(从根到最远的叶子)。
例如,考虑以下树:
10
/ \
6 13
/ \ \
4 9 14
/ /
3 8
我需要产生节点:8,9,6,10
我有这个Node 类:
class Node {
private:
Node *left;
Node *right;
int value;
public:
Node(int v = 0) : left(NULL) , right(NULL) , value(v) { cout << "Node construcotr " << endl;}
Node *getLeft() {return this->left;}
void setLeft(Node *n) {this->left = n;}
Node *getRight() {return this->right;}
void setRight(Node *n) {this->right = n;}
int getVal() {return this->value;}
};
这里是Tree类的相关部分:
class Tree {
private:
Node* root;
vector<int> vec; /*.....*/
int calcDepth(Node *n)
{
if (n == NULL)
return 0;
else
{
int ld = calcDepth(n->getLeft());
int rd = calcDepth(n->getRight());
if (ld > rd)
{
if (n->getLeft() != NULL) vec.push_back(n->getLeft()->getVal());
return ld + 1;
}
else
{
if (n->getRight() != NULL) vec.push_back(n->getRight()->getVal());
return rd + 1;
}
}
} // end of calcDepth
目前它给了我部分解决方案(不包括根并考虑到不属于该路径的节点)。
有人可以帮我修复这个代码吗?
此外,任何其他关于实现的 cmets 也会很棒。
【问题讨论】:
-
您能否向我们展示您的程序生成的实际输出(以及预期输出,如果它与给定示例不同)?请注意,提供SSCCE (Short, Self Contained, Correct (Compilable), Example)(强调自包含)会很有帮助,因此我们可以运行程序并自己查看结果,并测试我们的更改以查看它们是否有效。另请注意,这些问题通常很容易通过写下某些给定示例的每个步骤中程序应该执行的操作并从那里编写代码来解决。
标签: c++ algorithm binary-search-tree depth