Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define NOMINMAX
- #include <windows.h>
- #include <windowsx.h> // Add this line
- #include <commctrl.h>
- #include <string>
- #include <vector>
- #include <algorithm> // Add this at the top with other includes
- #include <functional>
- #include <ctime> // for time()
- #include <cstdlib> // for rand() and srand()
- #include <random>
- #include <sstream>
- #include <iostream>
- #include <richedit.h> // Include for Rich Edit control
- #include <shellapi.h>
- #pragma comment(lib, "Psapi.lib")
- #pragma comment(lib, "comctl32.lib") // Link with the common controls library
- //#pragma comment(lib, "riched32.lib") // Link with the rich edit library
- #pragma comment(lib, "Shell32.lib")
- // Structure for a binary tree node
- struct Node {
- int data;
- Node* left;
- Node* right;
- Node(int val) : data(val), left(nullptr), right(nullptr) {}
- };
- // Function to insert a new node into the binary tree
- Node* insert(Node* root, int val) {
- if (!root) {
- return new Node(val);
- }
- if (val < root->data) {
- root->left = insert(root->left, val);
- }
- else {
- root->right = insert(root->right, val);
- }
- return root;
- }
- // Helper function to get the height of the tree
- int getHeight(Node* root) {
- if (!root) return 0;
- return 1 + std::max(getHeight(root->left), getHeight(root->right));
- }
- // Helper function to add padding
- std::string getPadding(int level) {
- return std::string(level * 6, ' ');
- }
- std::string getListString(Node* root, std::string prefix = "") {
- if (!root) return "";
- std::string result = prefix + "|_ " + std::to_string(root->data) + "\r\n";
- if (root->left) {
- bool hasRight = (root->right != nullptr);
- std::string newPrefix = prefix + (hasRight ? "| " : " ");
- result += getListString(root->left, newPrefix);
- }
- if (root->right) {
- std::string newPrefix = prefix + " ";
- result += getListString(root->right, newPrefix);
- }
- return result;
- }
- void deleteTree(Node* node) {
- if (node) {
- deleteTree(node->left);
- deleteTree(node->right);
- delete node;
- }
- }
- // Modified getTreeString function with correct lambda capture
- std::string getTreeString(Node* root) {
- if (!root) return "";
- std::vector<std::string> levels; // levels vector
- //std::vector<std::string> levels;
- int maxLevelWidth = 0;
- levels.clear(); // Clear the levels vector at the beginning
- std::function<void(Node*, int, int)> traverse =
- [&](Node* node, int depth, int xOffset) {
- if (!node) return;
- // 1. Resize levels to accommodate current depth + children and connecting lines
- levels.resize(std::max((int)levels.size(), depth + 2)); // Ensure enough space
- int dataWidth = std::to_string(node->data).length();
- int centerX = xOffset + dataWidth / 2;
- // 2. Resize and pad level string for node data
- if (levels[depth].length() < centerX + dataWidth) {
- levels[depth].resize(centerX + dataWidth, ' ');
- }
- levels[depth].replace(centerX, dataWidth, std::to_string(node->data));
- maxLevelWidth = std::max(maxLevelWidth, (int)levels[depth].length());
- if (node->left || node->right) {
- int spacing = 3;
- int leftChildOffset = xOffset - spacing;
- int rightChildOffset = xOffset + dataWidth + spacing - 1;
- if (node->left) {
- // 3. Place left slash
- levels[depth + 1].resize(std::max((int)levels[depth + 1].length(), centerX), ' '); // Ensure space, pad if needed
- levels[depth + 1][centerX - 1] = '/';
- traverse(node->left, depth + 2, leftChildOffset);
- }
- if (node->right) {
- // 4. Place right slash
- levels[depth + 1].resize(std::max((int)levels[depth + 1].length(), centerX + 2), ' '); // Ensure space, pad if needed
- levels[depth + 1][centerX + 1] = '\\';
- traverse(node->right, depth + 2, rightChildOffset);
- }
- }
- };
- traverse(root, 0, 20);
- std::string result;
- for (size_t i = 0; i < levels.size(); ++i) {
- if (maxLevelWidth > levels[i].length()) {
- levels[i].resize(maxLevelWidth, ' ');
- }
- result += levels[i] + "\r\n";
- }
- return result;
- }
- LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
- int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) {
- const wchar_t CLASS_NAME[] = L"BinaryTreeVisualizer";
- WNDCLASS wc = { };
- wc.lpfnWndProc = WindowProc;
- wc.hInstance = hInstance;
- wc.lpszClassName = CLASS_NAME;
- RegisterClass(&wc);
- HWND hwnd = CreateWindowEx(
- 0, // Optional window styles.
- CLASS_NAME, // Window class
- L"Binary Tree Visualizer", // Window text
- WS_OVERLAPPEDWINDOW, // Window style
- CW_USEDEFAULT, CW_USEDEFAULT, 550, 400,
- NULL, // Parent window
- NULL, // Menu
- hInstance, // Instance handle
- NULL // Additional application data
- );
- if (hwnd == NULL) {
- return 0;
- }
- ShowWindow(hwnd, nCmdShow);
- // Run the message loop.
- MSG msg = { };
- while (GetMessage(&msg, NULL, 0, 0)) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- return 0;
- }
- LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
- static HWND hEdit, hDisplay, hTreeViewRadio, hListViewRadio, hGenerateButton;
- static Node* root = nullptr;
- switch (uMsg) {
- case WM_CREATE: {
- // Create Input Field
- hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", L"",
- WS_CHILD | WS_VISIBLE | WS_BORDER,
- 10, 10, 100, 20, hwnd, NULL, NULL, NULL);
- // Create multiline Edit control for display
- // Create display Edit control with proper styles for newlines
- hDisplay = CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", L"",
- WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL |
- ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | ES_LEFT,
- 10, 40, 510, 300, hwnd, NULL, NULL, NULL);
- // Radio Buttons
- hTreeViewRadio = CreateWindowEx(0, L"BUTTON", L"Tree View",
- WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON | WS_GROUP,
- 120, 10, 100, 20, hwnd, (HMENU)1, NULL, NULL);
- hListViewRadio = CreateWindowEx(0, L"BUTTON", L"List View",
- WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
- 230, 10, 100, 20, hwnd, (HMENU)2, NULL, NULL);
- // Generate Button
- hGenerateButton = CreateWindowEx(0, L"BUTTON", L"Generate Tree",
- WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
- 340, 10, 100, 20, hwnd, (HMENU)3, NULL, NULL);
- Button_SetCheck(hTreeViewRadio, BST_CHECKED);
- // Set monospace font
- // Set monospace font for better tree display
- HFONT hFont = CreateFont(16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
- DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
- DEFAULT_QUALITY, FIXED_PITCH | FF_MODERN, L"Consolas");
- SendMessage(hDisplay, WM_SETFONT, (WPARAM)hFont, TRUE);
- // Set tab stops for the display Edit control (optional)
- DWORD tabStops = 16; // in dialog units
- SendMessage(hDisplay, EM_SETTABSTOPS, 1, (LPARAM)&tabStops);
- // Set text alignment to center
- //SendMessage(hDisplay, EM_SETALIGNMENT, ES_CENTER, 0);
- break;
- }
- case WM_COMMAND:
- if (LOWORD(wParam) == 3) { // Generate button clicked
- wchar_t buffer[256];
- GetWindowText(hEdit, buffer, 256);
- wchar_t* endptr;
- long numNodes = std::wcstol(buffer, &endptr, 10);
- if (*endptr == L'\0' && numNodes > 0 && numNodes <= 100) {
- //delete root;
- deleteTree(root); // Correctly delete the entire tree
- root = nullptr;
- std::vector<int> numbers(numNodes);
- for (int i = 0; i < numNodes; ++i) {
- numbers[i] = i + 1;
- }
- std::random_device rd;
- std::mt19937 g(rd());
- std::shuffle(numbers.begin(), numbers.end(), g);
- for (int num : numbers) {
- root = insert(root, num);
- }
- std::string treeString;
- try {
- if (Button_GetCheck(hTreeViewRadio) == BST_CHECKED) {
- treeString = getTreeString(root);
- std::string::size_type pos = 0;
- while ((pos = treeString.find('\n', pos)) != std::string::npos) {
- treeString.replace(pos, 1, "\r\n");
- pos += 2;
- }
- }
- else {
- treeString = getListString(root);
- }
- int size_needed = MultiByteToWideChar(CP_UTF8, 0, treeString.c_str(), -1, NULL, 0);
- if (size_needed == 0) {
- OutputDebugString(L"MultiByteToWideChar failed\n");
- break;
- }
- std::wstring wideStr(size_needed - 1, 0);
- int converted_chars = MultiByteToWideChar(CP_UTF8, 0, treeString.c_str(), -1, &wideStr[0], size_needed);
- if (converted_chars == 0) {
- OutputDebugString(L"MultiByteToWideChar failed\n");
- break;
- }
- SetWindowText(hDisplay, wideStr.c_str());
- LONG_PTR style = GetWindowLongPtr(hDisplay, GWL_STYLE);
- style |= ES_MULTILINE | ES_AUTOVSCROLL;
- SetWindowLongPtr(hDisplay, GWL_STYLE, style);
- SendMessage(hDisplay, WM_VSCROLL, SB_TOP, 0);
- SendMessage(hDisplay, EM_SETSEL, 0, 0);
- SendMessage(hDisplay, EM_SCROLLCARET, 0, 0);
- }
- catch (const std::exception& e) {
- std::string error = "Exception: ";
- error += e.what();
- OutputDebugStringA(error.c_str());
- }
- }
- else {
- MessageBox(hwnd, L"Please enter a number between 1 and 100.", L"Invalid Input", MB_OK | MB_ICONWARNING);
- }
- }
- else if (LOWORD(wParam) == 1 || LOWORD(wParam) == 2) { // Radio button handling
- if (root != nullptr) {
- std::string treeString;
- if (Button_GetCheck(hTreeViewRadio) == BST_CHECKED) {
- treeString = getTreeString(root);
- std::string::size_type pos = 0;
- while ((pos = treeString.find('\n', pos)) != std::string::npos) {
- treeString.replace(pos, 1, "\r\n");
- pos += 2;
- }
- }
- else {
- treeString = getListString(root);
- }
- int size_needed = MultiByteToWideChar(CP_UTF8, 0, treeString.c_str(), -1, NULL, 0);
- if (size_needed == 0) {
- OutputDebugString(L"MultiByteToWideChar failed (Radio)\n");
- break;
- }
- std::wstring wideStr(size_needed - 1, 0);
- int converted = MultiByteToWideChar(CP_UTF8, 0, treeString.c_str(), -1, &wideStr[0], size_needed);
- if (converted == 0) {
- OutputDebugString(L"MultiByteToWideChar failed (Radio)\n");
- break;
- }
- SetWindowText(hDisplay, wideStr.c_str());
- LONG_PTR style = GetWindowLongPtr(hDisplay, GWL_STYLE);
- style |= ES_MULTILINE | ES_AUTOVSCROLL;
- SetWindowLongPtr(hDisplay, GWL_STYLE, style);
- SendMessage(hDisplay, WM_VSCROLL, SB_TOP, 0);
- SendMessage(hDisplay, EM_SETSEL, 0, 0);
- SendMessage(hDisplay, EM_SCROLLCARET, 0, 0);
- }
- }
- break;
- case WM_DESTROY:
- delete root; // Clean up
- PostQuitMessage(0);
- return 0;
- }
- return DefWindowProc(hwnd, uMsg, wParam, lParam);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement