[英]Displaying the nodes of binary search tree which belongs depth path of the tree
我在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
目前,它为我提供了部分解决方案(不包括根,并考虑了不属于该路径的节点)。
有人可以帮我解决此代码吗?
另外,关于实现的任何其他评论也将很棒。
您必须确保当它调用push_back
,它是路径中的节点之一。 由于您当前的算法会为每个节点添加节点。
class Tree {
private:
Node* root;
vector<int> vec; /*.....*/
int calcDepth(Node *n,int isInPath)
{
if (n == NULL)
return 0;
else
{
int ld = calcDepth(n->getLeft(),0);
int rd = calcDepth(n->getRight(),0);
if(isInPath){
vec.push_back(n->getVal());
if (ld > rd)
{
calcDepth(n->getLeft(),isInPath);
return ld + 1;
}
else
{
calcDepth(n->getRight(),isInPath);
return rd + 1;
}
}
return max(ld+1,rd+1);
}
} // end of calcDepth
我添加了一个变量isInPath
,如果当前节点在路径中,则为1;如果isInPath
,则为0。 您将使用root和1。
它查找两者中的最大值,然后才使用isInPath == 1
进行调用。 使用此方法,仅将isInPath == 1
节点添加到向量中。
我还没有测试过,但是应该可以。 您也可以将其创建为私有函数,然后再将其仅创建节点值作为公共函数。
注意:这具有O(N^2)
复杂度。 要使其成为O(N)
您可以记住这些值,这样就不必计算两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.