From 8bc581c068ff2cf9639fd10bf17f0961dd358484 Mon Sep 17 00:00:00 2001 From: Nikita Tokarchuk Date: Thu, 10 Feb 2022 17:06:06 +0100 Subject: [PATCH] Solution --- CMakeLists.txt | 6 +++ main.cpp | 109 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 main.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..14f97c5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.21) +project(tree_preorder_traversal) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(tree_preorder_traversal main.cpp) diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..7d0dd97 --- /dev/null +++ b/main.cpp @@ -0,0 +1,109 @@ +#include +#include +#include + +class Node { + public: + int data; + Node *left; + Node *right; + Node(int d) { + data = d; + left = NULL; + right = NULL; + } +}; + +class Solution { + public: + Node* insert(Node* root, int data) { + if(root == NULL) { + return new Node(data); + } else { + Node* cur; + if(data <= root->data) { + cur = insert(root->left, data); + root->left = cur; + } else { + cur = insert(root->right, data); + root->right = cur; + } + + return root; + } + } + +/* you only have to complete the function given below. +Node is defined as + +class Node { + public: + int data; + Node *left; + Node *right; + Node(int d) { + data = d; + left = NULL; + right = NULL; + } +}; + +*/ + +// void preOrder(Node *root) { +// /* #include */ +// std::deque q {root}; +// +// while (!q.empty()) { +// auto elem = q.back(); +// +// q.pop_back(); +// +// while (elem != nullptr) { +// if (elem->right != nullptr) { +// q.push_back(elem->right); +// } +// +// std::cout << elem->data << " "; +// +// elem = elem->left; +// } +// } +// } + + void printLeft(Node *left, Node *right) { + + while (left != nullptr) { + std::cout << " " << left->data; + + if (left->right != nullptr) { + printLeft(left->left, left->right); + break; + } + + left = left->left; + } + + if (right != nullptr) { + std::cout << " " << right->data; + + printLeft(right->left, right->right); + } + } + + void preOrder(Node *root) { + if (root == nullptr) { + return; + } + + std::cout << root->data; + + printLeft(root->left, root->right); + } + +}; //End of Solution + +int main() { + std::cout << "Hello, World!" << std::endl; + return 0; +}