-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathTrieNode.php
63 lines (55 loc) · 1.54 KB
/
TrieNode.php
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
<?php
/*
* Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed) in Pull Request #162 and #172
* https://github.com/TheAlgorithms/PHP/pull/162
* https://github.com/TheAlgorithms/PHP/pull/172
*
* Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request addressing bugs/corrections to this file.
* Thank you!
*/
namespace DataStructures\Trie;
class TrieNode
{
/** @var array<string, TrieNode> */
public array $children;
public bool $isEndOfWord;
public function __construct()
{
$this->children = []; // Associative array where [ char => TrieNode ]
$this->isEndOfWord = false;
}
/**
* Add a child node for a character.
*/
public function addChild(string $char): TrieNode
{
$char = $this->normalizeChar($char);
if (!isset($this->children[$char])) {
$this->children[$char] = new TrieNode();
}
return $this->children[$char];
}
/**
* Check if a character has a child node.
*/
public function hasChild(string $char): bool
{
$char = $this->normalizeChar($char);
return isset($this->children[$char]);
}
/**
* Get the child node corresponding to a character.
*/
public function getChild(string $char): ?TrieNode
{
$char = $this->normalizeChar($char);
return $this->children[$char] ?? null;
}
/**
* Normalize the character to lowercase.
*/
private function normalizeChar(string $char): string
{
return strtolower($char);
}
}