-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin_tree.cpp
More file actions
113 lines (92 loc) · 1.82 KB
/
Copy pathbin_tree.cpp
File metadata and controls
113 lines (92 loc) · 1.82 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Root = Index 0
Implementation of binary tree to
find index of left child, right child
and total number of childs of any node;
*/
#include<bits/stdc++.h>
#define ll long long
#define vll vector<ll>
#define pll pair<ll,ll>
#define pb push_back
#define MAX 105
using namespace std;
ll lchild[MAX], rchild[MAX], nchild[MAX];
void init()
{
for(ll i=0 ; i<MAX ; i++)
{
lchild[i]=-1;
rchild[i]=-1;
nchild[i]=0;
}
}
void dfs(ll s)
{
if(lchild[s]!=-1)
{
dfs(lchild[s]);
nchild[s]+=1+nchild[lchild[s]];
}
if(rchild[s]!=-1)
{
dfs(rchild[s]);
nchild[s]+=1+nchild[rchild[s]];
}
}
void solve()
{
init();
ll n;
cin>>n;
ll a[n];
for(ll i=0 ; i<n ; i++)
{
cin>>a[i];
}
ll root=a[0];
for(ll i=1 ; i<n ; i++)
{
ll j=0;
while(true)
{
if(a[i]>=a[j])
{
if(rchild[j]==-1)
{
rchild[j]=i;
break;
}
j=rchild[j];
}
else
{
if(lchild[j]==-1)
{
lchild[j]=i;
break;
}
j=lchild[j];
}
}
}
dfs(0);
for(ll i=0 ; i<n ; i++)
{
cout<<i<<' ';
cout<<lchild[i]<<' ';
cout<<rchild[i]<<' ';
cout<<nchild[i]<<' ';
cout<<endl;
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
freopen("input.txt","r",stdin);
solve();
return 0;
//Always comment out input.txt and output.txt
}