Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

In cây nhị phân 2D trong C++

In cây nhị phân trên màn hình 2D (xoay 90 độ). Gốc ở giữa, cây con phải in trước (trên), cây con trái in sau (dưới). Dùng đệ quy với tham số khoảng cách thụt lề.

Đệ quy in ngang

In cây con phải trước với space tăng dần. In nút hiện tại. In cây con trái. COUNT=10 khoảng cách mỗi cấp.

Ví dụ minh họa

#include <bits/stdc++.h>
using namespace std;

#define COUNT 10

struct Node {
    int data;
    Node *left, *right;
    Node(int d) : data(d), left(nullptr), right(nullptr) {}
};

void print2D(Node* root, int space) {
    if (!root) return;
    space += COUNT;
    print2D(root->right, space);
    for (int i = COUNT; i < space; i++) cout << '\t';
    cout << root->data << '\n';
    print2D(root->left, space);
}

int main() {
    Node* root = new Node(43);
    root->left = new Node(25);
    root->right = new Node(67);
    root->left->left = new Node(14);
    root->left->right = new Node(51);
    root->right->left = new Node(26);
    root->right->right = new Node(97);
    root->left->left->left = new Node(81);
    root->left->left->right = new Node(49);
    root->left->right->left = new Node(7);
    root->left->right->right = new Node(31);
    root->right->left->left = new Node(29);
    root->right->left->right = new Node(13);
    root->right->right->left = new Node(59);
    root->right->right->right = new Node(16);
    
    print2D(root, 0);
    return 0;
}

Kết quả

                16
        97
                59
    67
                13
        26
                29
43
                31
        51
                7
    25
                49
        14
                81