树——通用树结点数目、高度和度数的实现
生活随笔
收集整理的這篇文章主要介紹了
树——通用树结点数目、高度和度数的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1,樹中的屬性操作有:
?????? 1,樹中結點的數目,樹中高度,樹的度數;
??????
2,樹中結點數目:
?????? 1,定義功能:count(node)
????????????? 1,在 node 為根結點的樹中統計結點數目;
????????????? 2,遞歸實現;
2,功能函數代碼實現:
1 /* 求以 node 為根結點所代表的樹的結點數目,實現的很精妙 */ 2 int count(GTreeNode<T>* node) const // 公有的 count() 函數為 const 函數 3 { 4 int ret = 0; 5 6 if( node != NULL ) // 為空則直接是空樹的數目,0;第一種情況;如果 node 沒孩子,則 for 循環不會執行,返回 1; 7 { 8 ret = 1; // 至少已經有一個結點,第二種情況 9 10 for(node->child.move(0); !node->child.end(); node->child.next()) // 第三種情況 11 { 12 ret += count(node->child.current()); // 當前結點所擁有的孩子的數目,然后累加 13 } 14 } 15 16 return ret; 17 }??? 3,樹中結點成員函數代碼實現:
1 int count() const2 {
3 return count(root());
4 }?????????????
?
3,樹的高度:?
?????? 1,定義功能:height(node)
????????????? 1,獲取 node 為根結點的樹的高度;
????????????? 2,遞歸實現;
2,功能函數代碼實現:
1 /* 遞歸實現以 node 為根結點的樹的高度 */ 2 int height(GTreeNode<T>* node) const 3 { 4 int ret = 0; 5 6 if( node != NULL ) // 空樹高度為 0 7 { 8 for(node->child.move(0); !node->child.end(); node->child.next()) 9 { 10 int h = height(node->child.current()); // 求當前子樹高度 11 12 if( ret < h ) // 遍歷查找最大元素 13 { 14 ret = h; 15 } 16 } 17 18 ret = ret + 1; // 子樹的高度加上根結點的高度為當前樹的高度,包含了二、三兩種情況 19 } 20 21 return ret; 22 }3,樹的高度成員函數代碼實現:
1 int height() const2 {
3 return height(root());
4 }?
?
4,樹的度數:
??
?????? 1,定義功能:degree(node)
????????????? 1,獲取 node 為根結點的樹的度數;
????????????? 2,遞歸實現;
2,樹的度數功能函數代碼實現:
1 /* 遞歸實現以 node 為結點的樹的度數 */ 2 int degree(GTreeNode<T>* node) const 3 { 4 int ret = 0; 5 6 if( node != NULL ) // 空樹度數為 0 7 { 8 ret = node->child.length(); // 根結點孩子的數目 9 10 for(node->child.move(0); !node->child.end(); node->child.next()) 11 { 12 int d = degree(node->child.current()); // 每一顆子樹都求度數 13 14 if( ret < d ) // 當前度數較小,則保存最新求出來的度數,這里同時也包含了根結點的孩子數目 15 { 16 ret = d; // ret 是度數最大值,即樹的度數 17 } 18 } 19 } 20 21 return ret; 22 }??? ?3,樹的度數功能函數代碼實現:
1 /* 遞歸實現以 node 為結點的樹的度數 */ 2 int degree(GTreeNode<T>* node) const 3 { 4 int ret = 0; 5 6 if( node != NULL ) // 空樹度數為 0 7 { 8 ret = node->child.length(); // 根結點孩子的數目 9 10 for(node->child.move(0); !node->child.end(); node->child.next()) 11 { 12 int d = degree(node->child.current()); // 每一顆子樹都求度數 13 14 if( ret < d ) // 當前度數較小,則保存最新求出來的度數,這里同時也包含了根結點的孩子數目 15 { 16 ret = d; // ret 是度數最大值,即樹的度數 17 } 18 } 19 } 20 21 return ret; 22 }轉載于:https://www.cnblogs.com/dishengAndziyu/p/10925326.html
總結
以上是生活随笔為你收集整理的树——通用树结点数目、高度和度数的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 29 元类 异常
- 下一篇: Java 9.while语句