首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 類別封裝二叉樹:建立、三種遍歷、節點統計完整實作

     編輯:程式設計疑難解答

Btree 類別完整代碼

#include 
using namespace std;

struct TreeNode {
    int data;
    TreeNode *left, *right;
    TreeNode(int v): data(v), left(nullptr), right(nullptr) {}
};

class Btree {
    TreeNode *root;
    static int leafCount, degree1Count;
public:
    Btree(): root(nullptr) {}
    void insert(int x);           // BST 插入
    void preorder()  { preorder(root);  cout << endl; }
    void inorder()   { inorder(root);   cout << endl; }
    void postorder() { postorder(root); cout << endl; }
    int countNodes() { return count(root); }
    int countLeaves() { leafCount=0; countLeaves(root); return leafCount; }
    int countDegree1() { degree1Count=0; countDegree1(root); return degree1Count; }
private:
    void preorder(TreeNode* n)  { if(n){ cout<data<<" "; preorder(n->left); preorder(n->right); } }
    void inorder(TreeNode* n)   { if(n){ inorder(n->left); cout<data<<" "; inorder(n->right); } }
    void postorder(TreeNode* n) { if(n){ postorder(n->left); postorder(n->right); cout<data<<" "; } }
    int count(TreeNode* n) { return n ? count(n->left)+count(n->right)+1 : 0; }
    void countLeaves(TreeNode* n) {
        if(!n) return;
        if(!n->left && !n->right) leafCount++;
        else { countLeaves(n->left); countLeaves(n->right); }
    }
    void countDegree1(TreeNode* n) {
        if(!n) return;
        if((n->left && !n->right) || (!n->left && n->right)) degree1Count++;
        countDegree1(n->left); countDegree1(n->right);
    }
    void insert(TreeNode* &n, int x) { // 遞歸插入
        if(!n) n = new TreeNode(x);
        else if(x < n->data) insert(n->left, x);
        else insert(n->right, x);
    }
    void insert(int x) { insert(root, x); }
};
int Btree::leafCount = 0;
int Btree::degree1Count = 0;

int main() {
    Btree bt;
    int a[] = {7,4,2,3,15,35,6,45,55,20,1,14,56,57,58};
    for(int v: a) bt.insert(v);
    cout << "節點數:" << bt.countNodes() << endl;
    cout << "葉子數:" << bt.countLeaves() << endl;
    cout << "度=1節點數:" << bt.countDegree1() << endl;
    cout << "先序:"; bt.preorder();
    cout << "中序:"; bt.inorder();
    cout << "後序:"; bt.postorder();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved