50247. Build a Boolean Expression Tree

難度:4.5/5 Used Time: 22:00

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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "buildTree.h"

typedef struct{
Node* val;
int end_idx;
} info;

Node* new_node(char* c){
Node* n = (Node*) malloc(sizeof(Node));
n->val = c;
n->left = NULL, n->right = NULL;
return n;
}

info dfs(char* arr[], int l, int n){
if(arr[l][0] == '!'){
info next_info = dfs(arr, l + 1, n);
Node* this_node = new_node(arr[l]);
this_node->left = next_info.val;
this_node->right = NULL;
return (info) {this_node, next_info.end_idx};
}
else if(arr[l][0] == '('){
info left_info = dfs(arr, l + 1, n);
info right_info = dfs(arr, left_info.end_idx + 1, n);

Node* this_node = new_node(arr[left_info.end_idx]);
this_node->left = left_info.val;
this_node->right = right_info.val;
return (info) {this_node, right_info.end_idx + 1};
}
else {
return (info) {new_node(arr[l]), l + 1};
}
}

Node* buildTree(char* s){
char* exp[500005]; int n = 0;
char *token = strtok(s, " ");
while(token != NULL){
exp[n++] = token;
token = strtok(NULL, " ");
}
info ans_info = dfs(exp, 0, n);
return ans_info.val;
}

50247. Build a Boolean Expression Tree
https://aaronlin1229.github.io/judgegirl_50247/
Author
Akizumi
Posted on
July 17, 2023
Licensed under