50113. Ternary Search Tree

難度:2/5

沒想到如果root->val是\((-1,l)\)然後要插入的\(v > l\)時,要把root->改成\((l, n)\)

Second Try: 2/5 Used Time 13:20

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
#include <stdio.h>
#include <stdlib.h>
#include "construct.h"
#define MAXN 32768

// typedef struct node{
// int small, large;
// struct node *left, *mid, *right;
// } Node;

Node* new_node(){
Node* r = (Node*) malloc(sizeof(Node));
r->small = -1, r->large = -1;
r->left = NULL, r->mid = NULL, r->right = NULL;
return r;
}

Node* insert(Node* root, int val){
if(root == NULL){
Node* cur = new_node();
cur->large = val;
return cur;
}
else{
if(root->small == -1){
if(val < root->large) root->small = val;
else{
root->small = root->large;
root->large = val;
}
}
else{
if(val < root->small) root->left = insert(root->left, val);
else if(val > root->large) root->right = insert(root->right, val);
else root->mid = insert(root->mid, val);
}
return root;
}
}

Node* ConstructTree(int arr[], int n){
Node* root = NULL;
for(int i = 0; i < n; i++){
root = insert(root, arr[i]);
}
return root;
}


50113. Ternary Search Tree
https://aaronlin1229.github.io/judgegirl_50113/
Author
Akizumi
Posted on
July 17, 2023
Licensed under