簡體   English   中英

顯示屬於樹的深度路徑的二叉搜索樹的節點

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM