C/C++ 二叉樹

Sonui發表於2024-07-17

對於資料結構初學者二叉樹是一個很好的練習題目,這裡記錄一下二叉樹的一些操作。

查詢二叉樹有一個特性

對於所有的節點,都滿足左子樹上的所有節點都比自己的小,而右子樹上的所有節點都比自己大
————《挑戰程式設計競賽第二版》P78

#include <iostream>
#include <stdlib.h>

using namespace std;

typedef struct TreeNode
{
    int data;
    struct TreeNode *LT, *RT;
}TreeNode, *TreeList;

//建立一個葉子節點
TreeNode* creatTree(int pData){
    TreeNode *tree = (TreeNode*)malloc(sizeof(TreeNode));
    tree->data = pData;
    tree->LT = NULL;
    tree->RT = NULL;
    return tree;
}

int addLeaf(TreeList &node, int deep){
    //傳參需要注意,二叉樹是指標型別的,節點本身就是一個指標:*node。所以需要二級指標才能改變二叉樹的內容
    //TreeNode *node = NULL;
    char input;
    cin >> input;
    if(input != '#'){
        node = creatTree((int)input);
        addLeaf(node->LT, deep + 1);
        addLeaf(node->RT, deep + 1);
    } else{
        node = NULL;
    }
    return 1;
}

int treeInfo(TreeNode *tree, int deep){
    cout << "deep: " << deep << ", data: " << (char)tree->data << endl;
    if (tree->LT != NULL) treeInfo(tree->LT, deep + 1);
    if (tree->RT != NULL) treeInfo(tree->RT, deep + 1);
    return 0;
}

TreeNode *findValue(TreeNode *node, int value){
    if (node == NULL) return NULL;
    if (node->data == value) {
        cout << "ok, find it." << endl;
        return node;
    }
    else
        return findValue(node->data < value ? node->RT : node->LT, value);
    return NULL;
}

int main(){
    char data;
    TreeList tree, temp;
    addLeaf(tree, 0);
    cout << "start out info:" << endl;
    treeInfo(tree, 0);
    cout << "end out info" << endl;
    cout << "input a num to find: ";
    cin >> data;
    temp = findValue(tree, data);
    if (!temp) cout << "no find it." <<endl;
    else cout << "find in " << &temp << ", data: " << (char)temp->data << endl;

}

相關文章