显示属于树的深度路径的二叉搜索树的节点

问题描述 投票:0回答:1

我在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

目前它给了我部分解决方案(不包括根并考虑不属于该路径的节点)。

有人可以帮我修复这段代码吗?

此外,关于实施的任何其他评论也将是伟大的。

c++ algorithm binary-search-tree depth
1个回答
1
投票

您必须确保在调用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,如果是节点则为0。你将用root和1调用它。

它找到两者中的最大值,然后才用isInPath == 1调用。使用这个方法,只有带有isInPath == 1的节点才会被添加到向量中。

我没有测试过,但它应该工作。您还可以将其创建为私有函数,然后创建仅具有节点值的公共函数。

注意:这具有O(N ^ 2)复杂度。要在O(N)中进行设置,您可以记住这些值,这样就不会计算它们2次。

© www.soinside.com 2019 - 2024. All rights reserved.