> For the complete documentation index, see [llms.txt](https://leetcodebook-1.gitbook.io/top-interview-150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leetcodebook-1.gitbook.io/top-interview-150/trie/implement-trie-prefix-tree.md).

# 实现 Trie (前缀树)

题目链接: <https://leetcode.cn/problems/implement-trie-prefix-tree>

## 解题思路：

1. 按照每个字符串内字符出现的先后顺序构建字符串树
2. `search`函数遍历待查找字符串内的所有字符，遍历是否存在一条路线能构成待查找字符串
3. 若能则返回末端节点，否则返回`nil`

```go
type Trie struct {
	subChar []*Trie
	end     bool
}

func Constructor() Trie {
	return Trie{
		subChar: make([]*Trie, 26),
	}
}

func (this *Trie) Insert(word string) {
	node := this
	for _, char := range word {
		idx := char - 'a'
		if node.subChar[idx] == nil {
			sub := Constructor()
			node.subChar[idx] = &sub
		}
		node = node.subChar[idx]
	}
	node.end = true
}

func (this *Trie) search(word string) *Trie {
	node := this
	for _, char := range word {
		idx := char - 'a'
		if node.subChar[idx] == nil {
			return nil
		}
		node = node.subChar[idx]
	}
	return node
}
func (this *Trie) Search(word string) bool {
	node := this.search(word)
	if node == nil || !node.end {
		return false
	}
	return true
}

func (this *Trie) StartsWith(prefix string) bool {
	return this.search(prefix) != nil
}
```

## 复杂度分析

* **时间复杂度：** 时间复杂度为$$O(n)$$,$$n$$为字符串长度
* **空间复杂度：** 空间复杂度为$$O(n)$$,$$n$$为所有字符串的字符顺序数


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://leetcodebook-1.gitbook.io/top-interview-150/trie/implement-trie-prefix-tree.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
