main
Nikita Tokarchuk 3 years ago
parent 265180a09f
commit 8bc581c068
Signed by: mainnika
GPG Key ID: A595FB7E3E56911C
  1. 6
      CMakeLists.txt
  2. 109
      main.cpp

@ -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)

@ -0,0 +1,109 @@
#include <iostream>
#include <cstddef>
#include <deque>
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 <deque> */
// std::deque<Node*> 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;
}
Loading…
Cancel
Save