Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Comparing BSTs, Tries and TSTs

User image

Published by

sanya sanya

Published at: 3rd Aug, 2023
1.9 mins read

1. Structure:

- BST: Each node contains a string value and has two child nodes, with strings in the left subtree being smaller and strings in the right subtree being larger.

- Trie: Each node represents a character, and paths from the root to leaf nodes form complete strings. Each node can have multiple child nodes.

- TST: Each node contains a character and has three child pointers: left, middle, and right. It combines features of BSTs and tries.

2. String Retrieval:

- BST: String matching is exact using binary search but prefix matching is not directly supported.

- Trie: Tries excel at prefix matching, as each node represents a character, allowing retrieval of strings with common prefixes.

- TST: TSTs provide both retrieval based on exact string matches (similar to BSTs) and prefix matching capabilities (similar to tries).

3. Memory Usage:

- BST: Require additional memory for storing pointers to left and right child nodes, resulting in some memory overhead compared to tries and TSTs.

- Trie: Each node stores individual characters, resulting in increased memory usage, especially with many strings or long strings.

- TST: They require less memory than tries as they store characters at each node but avoid the overhead of storing pointers to left and right child nodes like BSTs.

4. Time Complexity:

- BST: The average and worst-case time complexity for operations in a balanced BST is O(log n), where n is the number of nodes. However, in the worst-case it can degrade to O(n).

- Trie: Tries have a time complexity of O(m), where m is the length of the search string.

- TST: TSTs have a time complexity of O(log n + k), where n is the number of nodes and k is the length of the search string.

5. Use Cases:

- BST: Suitable when maintaining a sorted order of strings is required and when exact string matches are the primary focus.

- Trie: Useful when efficient prefix matching is needed, such as in autocomplete systems, spell checkers, and IP routing tables.

- TST: TSTs are a good choice when both exact string matches and prefix matching are important, striking a balance between BSTs and tries.

Library

WEB DEVELOPMENT

FAANG QUESTIONS