博客 / 詳情

返回

C++ 自定義二叉樹並輸出二叉樹圖形

原文鏈接

使用C++構建一個二叉樹並輸出。

輸入

輸入根節點為10,依次輸入6、4、8、14、12、16

代碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include<iostream>
#include <stack> 
#include<cstdlib>

#include <string>
using namespace std;


struct TreeLinkNode         // 定義二叉樹
{
    int val;                       // 當前節點值用val表示
    struct TreeLinkNode *left;     // 指向左子樹的指針用left表示
    struct TreeLinkNode *right;    // 指向右子樹的指針用right表示
    struct TreeLinkNode *parent;  //指向父節點的指針用parent表示
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), parent(NULL) { } // 初始化當前結點值為x,左右子樹、父節點為空
};

//創建樹
TreeLinkNode* insert(TreeLinkNode* tree, int value)
{
    TreeLinkNode* node = (TreeLinkNode*)malloc(sizeof(TreeLinkNode)); // 創建一個節點
    node->val = value;      // 初始化節點
    node->left = NULL;
    node->right = NULL;
    node->parent = NULL;

    TreeLinkNode* temp = tree;      // 從樹根開始
    while (temp != NULL)
    {
        if (value < temp->val)  // 小於根節點就進左子樹
        {
            if (temp->left == NULL)
            {
                temp->left = node;  // 新插入的數為temp的左子樹
                node->parent = temp; // temp為新插入的數的父節點
                return tree;
            }
            else           // 下一輪判斷
                temp = temp->left;
        }
        else           // 否則進右子樹
        {    

            if (temp->right == NULL)
            {
                temp->right = node;  // 新插入的數為temp的右子樹
                node->parent = temp; // temp為新插入的數的父節點
                return tree;
            }
            else           // 下一輪判斷
                temp = temp->right;
        }
    }
    return tree;
}
 

//  ************* 輸出圖形二叉樹 *************
void output_impl(TreeLinkNode* n, bool left, string const& indent)
{
    if (n->right)
    {
        output_impl(n->right, false, indent + (left ? "|     " : "      "));
    }
    cout << indent;
    cout << (left ? '\\' : '/');
    cout << "-----";
    cout << n->val << endl;
    if (n->left)
    {
        output_impl(n->left, true, indent + (left ? "      " : "|     "));
    }
}
void output(TreeLinkNode* root)
{
    if (root->right)
    {
        output_impl(root->right, false, "");
    }
    cout << root->val << endl;
    if (root->left)
    {
        output_impl(root->left, true, "");
    }
    system("pause");
}
//  ***************************************



// ====================測試代碼====================
int main()
{

    TreeLinkNode tree = TreeLinkNode(10);       // 樹的根節點
    TreeLinkNode* treeresult;

    treeresult = insert(&tree, 6);         // 輸入n個數並創建這個樹
    treeresult = insert(&tree, 4);
    treeresult = insert(&tree, 8);
    treeresult = insert(&tree, 14);
    treeresult = insert(&tree, 12);
    treeresult = insert(&tree, 16);

    output(treeresult);         //  輸出圖形二叉樹

}

輸出

二叉樹2.png

學習更多編程知識,請關注我的公眾號:

代碼的路

公眾號二維碼.jpg

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.