forked from Minor-lazer/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarytree_diameter.cpp
123 lines (119 loc) · 1.96 KB
/
binarytree_diameter.cpp
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
114
115
116
117
118
119
120
121
122
123
//HACTOBERFEST
//Time compexity is O(n);
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Linkedlist{
ll data;
struct Linkedlist *left;
struct Linkedlist *right;
};
typedef struct Linkedlist *node;
ll fxn(node root,ll& ans)
{
if(root==NULL)
{
return 0;
}
else
{
ll lheight=fxn(root->left,ans);
ll rheight=fxn(root->right,ans);
ans=max(ans,1+lheight+rheight);
if(lheight>rheight)
{
return lheight+1;
}
else
{
return rheight+1;
}
}
}
int main()
{
ll t,x,i,u,j,ans;
string s;
cin>>t>>x;
node head=NULL,temp;
head=(node)malloc(sizeof(struct Linkedlist));
head->left=NULL;
head->right=NULL;
head->data=x;
for(j=1;j<=t-1;j++)
{
cin>>s>>x;
temp=NULL;
temp=head;
for(i=0;i<s.size();i++)
{
if(s[i]=='L')
{
if(temp->left==NULL)
{
node p=NULL;
p=(node)malloc(sizeof(struct Linkedlist));
temp->left=p;
p->left=NULL;
p->right=NULL;
}
else
{
temp=temp->left;
}
if(i==s.size()-1)
{
if(temp->left==NULL)
{
node p=NULL;
p=(node)malloc(sizeof(struct Linkedlist));
temp->left=p;
p->left=NULL;
p->right=NULL;
p->data=x;
}
else
{
temp=temp->left;
temp->data=x;
}
}
}
else
{
if(temp->right==NULL)
{
node p=NULL;
p=(node)malloc(sizeof(struct Linkedlist));
temp->right=p;
p->right=NULL;
p->left=NULL;
}
else
{
temp=temp->right;
}
if(i==s.size()-1)
{
if(temp->right==NULL)
{
node p=NULL;
p=(node)malloc(sizeof(struct Linkedlist));
temp->right=p;
p->left=NULL;
p->right=NULL;
p->data=x;
}
else
{
temp=temp->right;
temp->data=x;
}
}
}
}
}
ans=0; //if no node exist then diameter will be 0
ll te=fxn(head,ans); //te value has no significance.It is used just to store the return value...we have our diameter in ans
cout<<ans<<"\n";
}