Trie 字典树 删除操作

字典树的删除操作:

1 没找到直接返回

2 找到叶子节点的时候,叶子节点的count标志清零,代表不是叶子节点了

3 如果当前节点没有其他孩子节点的时候,可以删除这个节点

判断是否需是叶子节点,就检查叶子节点的count标志就可以了。

判断是否有其他孩子节点就需要循环26个节点了,如果都为空,那么就没有其他孩子节点了。


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>

class TrieDelete_2
{
	static const int ARRAY_SIZE = 26;
	struct Node
	{
		int val;
		Node *children[ARRAY_SIZE];
		explicit Node(int k = 0) : val(k)
		{
			for (int i = 0; i < ARRAY_SIZE; i++)
			{
				children[i] = NULL;
			}
		}
		~Node()
		{
			for (int i = 0; i < ARRAY_SIZE; i++)
			{
				if (children[i]) delete children[i];
				children[i] = NULL;
			}
		}
	};

	struct Trie
	{
		Node *emRoot;
		int count;
		explicit Trie(int c = 0) : count(c)
		{
			emRoot = new Node;//emRoot(NULL) {},应该分配emRot空间比较合理
		}
		~Trie()
		{
			if (emRoot) delete emRoot;
			emRoot = NULL;
		}
	};

	void insert(Trie *trie, char keys[])
	{
		int len = strlen(keys);

		Node *pCrawl = trie->emRoot;
		trie->count++;

		for (int i = 0; i < len; i++)
		{
			int k = keys[i] - 'a';
			if (!pCrawl->children[k])
			{
				pCrawl->children[k] = new Node;
			}
			pCrawl = pCrawl->children[k];
		}
		pCrawl->val = trie->count;
	}

	bool search(Trie *trie, char key[])
	{
		int len = strlen(key);
		Node *pCrawl = trie->emRoot;
		for (int i = 0; i < len; i++)
		{
			int k = key[i] - 'a';
			if (!pCrawl->children[k])
			{
				return false;
			}
			pCrawl = pCrawl->children[k];
		}
		return pCrawl->val != 0;
	}

	bool isFreeNode(Node *n)
	{
		for (int i = 0; i < ARRAY_SIZE; i++)
		{
			if (n->children[i]) return false;
		}
		return true;
	}

	bool isLeaf(Node *n)
	{
		return n->val != 0;
	}

	bool deleteHelp(Node *n, char key[], int lv, int len)
	{
		if (n)
		{
			if (lv == len)
			{
				if (isLeaf(n))
				{
					n->val = 0;
					if (isFreeNode(n))
					{
						delete n, n = NULL;
						return true;
					}
					return false;
				}
			}
			else
			{
				int k = key[lv] - 'a';
				if(deleteHelp(n->children[k], key, lv+1, len))
				{
					if (!isLeaf(n) && isFreeNode(n))
					{
						delete n, n = NULL;
						return true;
					}
					return false;
				}
			}
		}
		return false;
	}

	void deleteKey(Trie *trie, char key[])
	{
		int len = strlen(key);
		if (len > 0)
		{
			deleteHelp(trie->emRoot, key, 0, len);
		}
	}

public:
	TrieDelete_2()
	{
		char keys[][8] = {"she", "sells", "sea", "shore", "the", "by", "sheer"};
		Trie *trie = new Trie; 

		for(int i = 0; i < ARRAY_SIZE(keys); i++)
		{
			insert(trie, keys[i]);
		}

		deleteKey(trie, keys[0]);

		printf("%s %s\n", "she", search(trie, "she") ? "Present in trie" : "Not present in trie");

		delete trie;
	}
};


### 回答1: Trie字典树的Java代码实现可以分为以下几部分: 1. 定义Trie节点类,包含children数组和isEndOfWord标识,用于表示是否是单词的结尾。 2. 定义Trie类,包含插入、查找和删除操作。 3. 在Trie类中实现插入操作,遍历字符串每一个字符,在Trie树中寻找对应节点,如果不存在则新建节点。 4. 在Trie类中实现查找操作,遍历字符串每一个字符,在Trie树中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则说明字符串是单词。 5. 在Trie类中实现删除操作,遍历字符串每一个字符,在Trie树中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则将其设为false,并删除空节点。 如果需要完整代码和注释请告诉我。 ### 回答2: Trie字典树)是一种常用的数据结构,用于高效地存储和查找字符串。下面是Trie字典树的Java代码实现,用于返回单词。 ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 字母表的大小为26 isEndOfWord = false; } public void insert(String word) { TrieNode curr = this; for (char c : word.toCharArray()) { if (curr.children[c - 'a'] == null) { curr.children[c - 'a'] = new TrieNode(); } curr = curr.children[c - 'a']; } curr.isEndOfWord = true; } public boolean search(String word) { TrieNode node = searchPrefix(word); return node != null && node.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String prefix) { TrieNode curr = this; for (char c : prefix.toCharArray()) { if (curr.children[c - 'a'] == null) { return null; } curr = curr.children[c - 'a']; } return curr; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { root.insert(word); } public boolean search(String word) { return root.search(word); } public boolean startsWith(String prefix) { return root.startsWith(prefix); } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); trie.insert("app"); System.out.println(trie.search("apple")); // 输出:true System.out.println(trie.startsWith("app")); // 输出:true System.out.println(trie.search("banana")); // 输出:false } } ``` 以上代码中,`TrieNode`表示Trie的节点,`Trie`表示Trie树的结构。其中`TrieNode`类包含了插入单词、查找单词(完全匹配)以及查找前缀的功能。`Trie`类则是对外提供插入、查找单词和前缀的方法。 在`main`方法中,我们演示了如何使用`Trie`类来插入和查找单词。首先,我们插入了两个单词"apple"和"app"。然后分别调用`search`方法来查找"apple"和"banana",以及`startsWith`方法来查找以"app"开头的单词。最后,打印出对应的结果,即是否找到了对应的单词或前缀。 以上是Trie字典树的Java代码实现,用于返回单词。 ### 回答3: Trie字典树是一种经典的数据结构,用于高效地存储和查找字符串集合。下面是一个基于Java的Trie字典树的代码实现,可以实现返回单词的功能: ```java class TrieNode { private final int ALPHABET_SIZE = 26; private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[ALPHABET_SIZE]; isEndOfWord = false; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return current != null && current.isEndOfWord; } public List<String> getAllWords() { List<String> result = new ArrayList<>(); TrieNode current = root; StringBuilder sb = new StringBuilder(); getAllWordsUtil(current, sb, result); return result; } private void getAllWordsUtil(TrieNode node, StringBuilder sb, List<String> result) { if (node == null) { return; } if (node.isEndOfWord) { result.add(sb.toString()); } for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { sb.append((char)('a' + i)); getAllWordsUtil(node.children[i], sb, result); sb.deleteCharAt(sb.length() - 1); } } } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); String[] words = {"hello", "world", "java", "programming"}; for (String word : words) { trie.insert(word); } List<String> allWords = trie.getAllWords(); System.out.println("All words in trie: " + allWords); } } ``` 上述代码中,TrieNode类表示字典树的节点,包括一个指向子节点的数组和一个标记,用于表示节点是否是某个单词的结尾。Trie类封装了字典树操作,包括插入单词、查找单词和返回所有单词的功能。在代码的主函数中,我们创建一个Trie对象并插入一些单词,然后调用getAllWords()方法返回字典树中的所有单词。最后,打印出返回的单词列表。 希望以上解答对您有所帮助,如有更多疑问,请继续追问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值