所謂二元樹的串列表示法就是利用鏈結串列來儲存二元樹, 也就是利用動態記憶體及指標的方式來建立二元樹. 其節點宣告如下 :
- class LSBinaryTreeNode{
- public:
- int data;
- class LSBinaryTreeNode *left;
- class LSBinaryTreeNode *right;
- LSBinaryTreeNode(){
- data = -1;
- left = NULL;
- right = NULL;
- }
- };
* LSBinaryTree.h 代碼 :
- #include
- using namespace std;
- class LSBinaryTreeNode{
- public:
- int data;
- class LSBinaryTreeNode *left;
- class LSBinaryTreeNode *right;
- LSBinaryTreeNode(){
- data = -1;
- left = NULL;
- right = NULL;
- }
- };
- typedef class LSBinaryTreeNode lsbtNode;
- typedef lsbtNode *lsbtNodePoint;
- class LSBinaryTree{
- lsbtNodePoint rootNode;
- public:
- LSBinaryTree(){
- rootNode = NULL;
- }
- virtual void add_Node_To_Tree(int value);
- virtual int getLevel(); /*獲取此二元樹的Level/階度*/
- virtual int getNodeCount(); /*獲取此二元樹的設定節點個數*/
- protected:
- virtual int _getNodeCount(lsbtNodePoint p);
- virtual int _getDepth(lsbtNodePoint p);
- };
- #include "LSBinaryTree.h"
- void LSBinaryTree::add_Node_To_Tree(int value) {
- lsbtNodePoint currentNode;
- lsbtNodePoint newnode;
- int flag=0; // 用來紀錄是否插入新的節點
- newnode = (lsbtNodePoint)malloc(sizeof(lsbtNode));
- newnode->data = value;
- newnode->left = NULL;
- newnode->right = NULL;
- if(this->rootNode == NULL){
- rootNode = newnode;
- } else {
- currentNode = this->rootNode;
- while(!flag) {
- if(value<=currentNode->data) { // 往左子樹
- if(currentNode->left == NULL) {
- currentNode->left = newnode;
- flag = 1;
- } else {
- currentNode = currentNode->left;
- }
- } else { // 往右子樹
- if(currentNode->right == NULL){
- currentNode->right = newnode;
- flag = 1;
- } else {
- currentNode = currentNode->right;
- }
- }
- }
- }
- }
- int LSBinaryTree::getLevel() {
- return _getDepth(this->rootNode);
- }
- int LSBinaryTree::getNodeCount() {
- return _getNodeCount(this->rootNode);
- }
- int LSBinaryTree::_getNodeCount(lsbtNodePoint p){
- if(p!=NULL) {
- return this->_getNodeCount(p->left) + this->_getNodeCount(p->right) + 1;
- } else {
- return 0;
- }
- }
- int LSBinaryTree::_getDepth(lsbtNodePoint p){
- if(p!=NULL) {
- int ld = 1+ this->_getDepth(p->left);
- int rd = 1+ this->_getDepth(p->right);
- if(ld>rd) {
- return ld;
- } else {
- return rd;
- }
- } else {
- return 0;
- }
- }
- void ch06_02(bool b) {
- if(b) {
- int value=0;
- LSBinaryTree btree;
- while(true) {
- cout << "請輸入節點值(輸入-1離開): ";
- cin >> value;
- if(value == -1)
- break;
- else
- btree.add_Node_To_Tree(value);
- }
- cout << ">>>你總共輸入 " << btree.getNodeCount() << " 個節點." << endl;
- cout << ">>>該二元樹階度為 " << btree.getLevel() << endl;
- }
- }
執行結果 :
根據輸入, 二元樹如下所示 :
沒有留言:
張貼留言