-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path192.cpp
More file actions
50 lines (43 loc) · 910 Bytes
/
Copy path192.cpp
File metadata and controls
50 lines (43 loc) · 910 Bytes
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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *left,*right;
Node(int x){
data=x;
left=right=NULL;
}
};
void preorderRecursion(Node *root){
if(root){
cout<<root->data<<" ";
preorderRecursion(root->left);
preorderRecursion(root->right);
}
}
Node * f(string s,int &i){
if(s.size()==0 || i>=s.size()) return NULL;
int num=0;
while(i<s.size() && s[i]!='(' && s[i]!=')'){
num=num*10+(s[i]-'0');
i++;
}
Node *root=NULL;
if(num>0) root=new Node(num);
if(i<s.size() && s[i]=='(') root->left=f(s,++i);
if(i<s.size() && s[i]==')'){
i++;
return root;
}
if(i<s.size() && s[i]=='(') root->right=f(s,++i);
if(i<s.size() && s[i]==')') i++;
return root;
}
int main(){
string s="4(2(3)(1))(6(5))";
int i=0;
Node *root=f(s,i);
preorderRecursion(root);
return 0;
}