📜  在C / C ++中使用图形表示树

📅  最后修改于: 2021-05-31 23:14:26             🧑  作者: Mango

先决条件: graphics.h,如何包含graphics.h?

在C / C++中,有graphics.h头文件,用于创建线,圆等对象。
给定N个整数的数组arr [] ,任务是编写C++程序以使用graphics.h创建Tree。

方法:要运行该程序,我们包含以下头文件:

#include 

我们将通过以下功能创建树:

  1. setcolor(color) 此函数存在于graphic.h头文件中,该头文件用于将当前图形颜色设置为新颜色。
  2. floodfill(pattern,color) 用于填充封闭区域的函数。当前的填充图案和填充颜色用于填充区域。
  3. circle(x,y,radius) 头文件graphics.h包含circle()函数,该函数绘制一个以(x,y)为中心且给定半径的圆。
  4. outtextxy() 头文件graphics.h包含outtextxy()函数,该函数在屏幕上的指定点(x,y)上显示文本或字符串。

以下是使用C++中的图形绘制Tree的实现:

C++
// C++ program to draw the tree
// in graphics.h
#include 
#include 
#include 
#include 
using namespace std;
 
// Function that prints Tree using
// functions graphic.h header file
void printTree(int x, int y, int* array,
               int index,
               int total_elements)
{
 
    // Base Case
    if (index >= total_elements)
        return NULL;
 
    // Convert int value into string
    ostringstream str1;
    str1 << array[index];
 
    string str2 = str1.str();
    char* str = &str2[0u];
 
    // Set color of the boundary of
    // circle as green
    setcolor(GREEN);
 
    // Draw the circle of radius 15
    // that represent node of Tree
    circle(x, y, 15);
    floodfill(x, y, GREEN);
 
    // Print the values of the node
    // in the circle
    outtextxy(x - 2, y - 3, str);
 
    // Set the color of the line
    // from parent to child as green
    setcolor(GREEN);
 
    // Evaluating left and right child
    int left = 2 * index + 1;
    int right = 2 * index + 2;
 
    // Recursively draw the left subtree
    // and the right subtree
    printTree(x - y / (index + 1), y + 50,
              array, left, total_elements);
 
    printTree(x + y / (index + 1), y + 50,
              array, right, total_elements);
 
    // Draw the line (or link) when the
    // node is not the leaf node
    if (left < total_elements) {
        line(x, y, x - y / (index + 1), y + 50);
    }
 
    if (right < total_elements) {
        line(x, y, x + y / (index + 1), y + 50);
    }
 
    return NULL;
}
 
// Driver Code
int main()
{
    // Initialize graphic driver
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "None");
 
    // Consider the tree as represented
    /*
             1
          /     \
         2       3
       /  \     / \
      4   5    6   7
     / \  /
     8  9 10
    */
 
    // Given array arr[]
    int array[] = { 1, 2, 3, 4, 5,
                    6, 7, 8, 9, 10 };
 
    // Function Call
    printTree(300, 100, array, 0, 10);
    getch();
 
    // closegraph function closes the
    // graphics mode and deallocates
    // all memory allocated by
    // graphics system
    closegraph();
}


输出:

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”