/
print_tree.cc
100 lines (83 loc) · 1.92 KB
/
print_tree.cc
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
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
#include <string>
using namespace std;
// Data structure to store a binary tree node
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};
struct Trunk
{
Trunk *prev;
string str;
Trunk(Trunk *prev, string str)
{
this->prev = prev;
this->str = str;
}
};
// Helper function to print branches of the binary tree
void showTrunks(Trunk *p)
{
if (p == nullptr) {
return;
}
showTrunks(p->prev);
cout << p->str;
}
void printTree(Node* root, Trunk *prev, bool isLeft)
{
if (root == nullptr) {
return;
}
string prev_str = " ";
Trunk *trunk = new Trunk(prev, prev_str);
printTree(root->right, trunk, true);
if (!prev) {
trunk->str = "———";
}
else if (isLeft)
{
trunk->str = ".———";
prev_str = " |";
}
else {
trunk->str = "`———";
prev->str = prev_str;
}
showTrunks(trunk);
cout << " " << root->data << endl;
if (prev) {
prev->str = prev_str;
}
trunk->str = " |";
printTree(root->left, trunk, false);
}
int main()
{
// Construct above tree
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->left->left->left = new Node(8);
root->left->left->right = new Node(9);
root->left->right->left = new Node(10);
root->left->right->right = new Node(11);
root->right->left->left = new Node(12);
root->right->left->right = new Node(13);
root->right->right->left = new Node(14);
root->right->right->right = new Node(15);
// print constructed binary tree
printTree(root, nullptr, false);
return 0;
}