Skip to content

Commit 6858ac6

Browse files
committed
Binary tree
1 parent 9d8fd1d commit 6858ac6

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Tree/BinaryTree.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// Node class
6+
class Node
7+
{
8+
public:
9+
int data;
10+
Node *left;
11+
Node *right;
12+
13+
Node(int val)
14+
{
15+
data = val;
16+
left = right = NULL;
17+
}
18+
};
19+
20+
static int idx = -1;
21+
Node *buildTree(vector<int> preorder)
22+
{
23+
idx++;
24+
25+
// base case
26+
if (preorder[idx] == -1)
27+
{
28+
return NULL;
29+
}
30+
31+
// create root node
32+
Node *root = new Node(preorder[idx]);
33+
34+
// left sub tree recursion call
35+
root->left = buildTree(preorder);
36+
37+
// left sub tree recursion call
38+
root->right = buildTree(preorder);
39+
40+
return root;
41+
}
42+
43+
int main()
44+
{
45+
vector<int> preorder = {1, 2, -1, -1, 3, 4, -1, -1, 5, -1, -1};
46+
47+
Node *root = buildTree(preorder);
48+
49+
cout << root->data << endl;
50+
cout << root->left->data << endl;
51+
cout << root->right->data << endl;
52+
53+
return 0;
54+
}

Tree/BinaryTree.exe

66.4 KB
Binary file not shown.

0 commit comments

Comments
 (0)