【问题标题】:Displaying the nodes of binary search tree which belongs depth path of the tree显示属于树深度路径的二叉搜索树的节点
【发布时间】: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


【解决方案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 次。

【讨论】:

  • @ Dragos Florian Ristache:谢谢分配 Dragos。但是我不了解您对 O(N) 复杂性的解决方案,您能否更具体一些。此外,我需要稍微改变函数的原型,以便它(从调用函数)接收向量来存储最长路径的节点。你的意思是记住我们需要一些额外的向量来表示这些值吗?如果您可以将解决方案更改为具有更好复杂性(在运行时)的解决方案,那将会很棒,如果它需要更多空间 - 可以提供它。
  • @ Dragos Florian Ristache:新原型是 int calcDepth(Node *n,int isInPath, vector &vec) 以便从调用函数(main 或其他...)提供 vec
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
相关资源
最近更新 更多