-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathGenricTree.cpp
67 lines (50 loc) Β· 1.1 KB
/
GenricTree.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
#include <bits/stdc++.h>
using namespace std;
//https://www.geeksforgeeks.org/generic-treesn-array-trees/
// defining node
class node{
public:
int data;
vector<node*> children;
node(int val){
this->data=val;
}
};
//function to create genric tree (n)
void creatingtree(node* &root,int arr[],int n){
stack<node*> st;
for(int i=0;i<n;i++){
if(arr[i]==-1){
st.pop();
}
else{
node* newnode= new node(arr[i]);
if(st.size()>0){
st.top()->children.push_back(newnode);
}
else{
root=newnode;
}
st.push(newnode);
}
}
}
// function to display the genric tree (n)
void display(node* root){
string str=to_string(root->data)+"->";
for(node*child:root->children){
str +=to_string(child->data)+", ";
}
str+=".";
cout<<str<<endl;
for(node*child:root->children){
display(child);
}
}
int main(){
node* root=NULL;
int arr[]={10,20,50,-1,60,-1,-1,30,70,-1,80,110,-1,120,-1,-1,90,-1,-1,40,100,-1,-1,-1};
int n=sizeof(arr)/sizeof(arr[0]);
creatingtree(root,arr,n);
display(root);
}