樹——二叉樹結點的查找


1,查找方式:

       1,基於數據元素值的查找:

              1,BTreeNode<T>* find(const T& value) const

       2,基於結點的查找:

              1,BTreeNode<T>* find(TreeNode<T>* node) const 

            

2,樹中數據元素和結點的查找:

 

      

3,基於數據元素值的查找:

 

       1,定義功能:find(node, value)

              1,在 node 為根結點的二叉樹中查找 value 所在的結點:

       2,功能函數代碼實現:

 1    /*定義按照值查找的遞歸功能函數*/
 2    virtual BTreeNode<T>* find(BTreeNode<T>* node, const T& value) const  
 3     {
 4         BTreeNode<T>* ret = NULL;
 5 
 6         if( node != NULL )  // 查找的不是空結點
 7         {
 8             if( node->value == value )  // 根結點值相等,則找到了
 9             {
10                 ret = node;
11             }
12             else
13             {
14                 if( ret == NULL )  // 根結點沒有查到,查左子樹
15                 {
16                     ret = find(node->left, value);
17                 }
18 
19                 if( ret == NULL )  // 左子樹沒有查到,查右子樹
20                 {
21                     ret =  find(node->right, value);
22                 }
23             }
24         }
25 
26         return ret;
27    }

  3,成員函數的代碼實現:

1 BTreeNode<T>* find(const T& value) const 

2 {

3 return find(root(), value);

4 }
 

4,基於結點的查找:

       1,定義功能:find(node, obj)

              1,在 node 為根結點的二叉樹中查找是否存在 obj 結點;

  2,功能函數代碼實現:

 1    /*定義按照結點查找的遞歸功能函數*/
 2     virtual BTreeNode<T>* find(BTreeNode<T>* node, BTreeNode<T>* obj) const
 3     {
 4         BTreeNode<T>* ret = NULL;
 5 
 6         if( node == obj )  // 如果是根結點
 7         {
 8             ret = node;  // 地址賦值給返回值
 9         }
10         else
11         {
12             if( node != NULL )  // 查找結點非空
13             {
14                 if( ret == NULL )  // 不是根結點
15                 {
16                     ret = find(node->left, obj);  // 查找左子樹
17                 }
18 
19                 if( ret == NULL )
20                 {
21                     ret = find(node->right, obj);  // 查找右子樹
22                 }
23             }
24         }
25 
26         return ret;
27    }

       3,成員函數代碼實現:

1 BTreeNode<T>* find(TreeNode<T>* node) const 

2 {

3 return find(root(), dynamic_cast<BTreeNode<T>*>(node));

4 }
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM