-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeek6_2.cpp
More file actions
87 lines (76 loc) · 1.51 KB
/
Copy pathWeek6_2.cpp
File metadata and controls
87 lines (76 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
ทำ Binary Tree
Using iterative to insert
*/
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
Node *newNode(int key)
{
Node *node = new Node;
node->data = key;
node->left = node->right = nullptr;
return node;
}
void printTree(Node *root, int space)
{
//ผมพยายามไม่ทำเป็น recursive แต่ไม่รอดครับ
if (root == nullptr)
return;
space += 10;
printTree(root->left, space);
cout << endl;
for (int i = 10; i < space; i++)
cout << " ";
cout << root->data;
printTree(root->right, space);
}
void insertIterative(Node *&root, int key)
{
Node *curr = root;
Node *parent = nullptr;
if (root == nullptr)
{
root = newNode(key);
return;
}
while (curr != nullptr)
{
parent = curr;
if (key < curr->data)
{
curr = curr->left;
}
else
{
curr = curr->right;
}
}
if (key < parent->data)
{
parent->left = newNode(key);
}
else
{
parent->right = newNode(key);
}
}
main()
{
int n;
cout << "Enter amount of element" << endl;
cin >> n;
cout << "Enter data:" << endl;
int* num = new int[n];
for(int i=0;i<n;i++)
cin >> num[i];
Node *root = nullptr;
for (int i=0;i<n;i++)
insertIterative(root, num[i]);
cout << "Binary Tree:" << endl;
printTree(root, 0);
}