diff --git a/README.md b/README.md index d495c0a7b..bac0bf373 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ ## To-Dos -- [x] [代码翻译](https://github.com/krahets/hello-algo/issues/15)(JavaScript, TypeScript, C, C++, C#, ... 寻求大佬帮助) +- [x] [代码翻译](https://github.com/krahets/hello-algo/issues/15):Java, C++, Python, Go, JavaScript 正在进行中,其他语言请求大佬挑大梁 - [ ] 数据结构:散列表、堆(优先队列)、图 - [ ] 算法:搜索与回溯、选择 / 堆排序、动态规划、贪心、分治 diff --git a/codes/cpp/chapter_stack_and_queue/deque.cpp b/codes/cpp/chapter_stack_and_queue/deque.cpp index 820dd4af2..96cf58111 100644 --- a/codes/cpp/chapter_stack_and_queue/deque.cpp +++ b/codes/cpp/chapter_stack_and_queue/deque.cpp @@ -21,7 +21,7 @@ int main() { cout << "双向队列 deque = "; PrintUtil::printDeque(deque); - /* 访问队首元素 */ + /* 访问元素 */ int front = deque.front(); cout << "队首元素 front = " << front << endl; int back = deque.back(); diff --git a/codes/go/chapter_computational_complexity/leetcode_two_sum_test.go b/codes/go/chapter_computational_complexity/leetcode_two_sum_test.go index b787c65b2..6e44eef98 100644 --- a/codes/go/chapter_computational_complexity/leetcode_two_sum_test.go +++ b/codes/go/chapter_computational_complexity/leetcode_two_sum_test.go @@ -5,6 +5,7 @@ package chapter_computational_complexity import ( + "fmt" "testing" ) @@ -16,8 +17,8 @@ func TestTwoSum(t *testing.T) { // ====== Driver Code ====== // 方法一:暴力解法 res := twoSumBruteForce(nums, target) - t.Log("方法一 res =", res) + fmt.Println("方法一 res =", res) // 方法二:哈希表 res = twoSumHashTable(nums, target) - t.Log("方法二 res =", res) + fmt.Println("方法二 res =", res) } diff --git a/codes/go/chapter_searching/linear_search_test.go b/codes/go/chapter_searching/linear_search_test.go index c24064424..79525aace 100644 --- a/codes/go/chapter_searching/linear_search_test.go +++ b/codes/go/chapter_searching/linear_search_test.go @@ -5,6 +5,7 @@ package chapter_searching import ( + "fmt" "testing" . "github.com/krahets/hello-algo/pkg" @@ -16,10 +17,10 @@ func TestLinearSearch(t *testing.T) { // 在数组中执行线性查找 index := linerSearchArray(nums, target) - t.Log("目标元素 3 的索引 =", index) + fmt.Println("目标元素 3 的索引 =", index) // 在链表中执行线性查找 head := ArrayToLinkedList(nums) node := linerSearchLinkedList(head, target) - t.Log("目标结点值 3 的对应结点对象为", node) + fmt.Println("目标结点值 3 的对应结点对象为", node) } diff --git a/codes/go/chapter_stack_and_queue/array_queue.go b/codes/go/chapter_stack_and_queue/array_queue.go index fd41f8bae..863768ba8 100644 --- a/codes/go/chapter_stack_and_queue/array_queue.go +++ b/codes/go/chapter_stack_and_queue/array_queue.go @@ -4,50 +4,45 @@ package chapter_stack_and_queue -import ( - "fmt" - "strings" -) - -// ArrayQueue 基于环形数组实现的队列, 不支持扩容 +/* 基于环形数组实现的队列 */ type ArrayQueue struct { - data []any // 用于存储队列元素的数组 + data []int // 用于存储队列元素的数组 capacity int // 队列容量(即最多容量的元素个数) - head int // 头指针,指向队首 - tail int // 尾指针,指向队尾 + 1 + front int // 头指针,指向队首 + rear int // 尾指针,指向队尾 + 1 } // NewArrayQueue 基于环形数组实现的队列 func NewArrayQueue(capacity int) *ArrayQueue { return &ArrayQueue{ - data: make([]any, capacity), + data: make([]int, capacity), capacity: capacity, - head: 0, - tail: 0, + front: 0, + rear: 0, } } // Size 获取队列的长度 func (q *ArrayQueue) Size() int { - size := (q.capacity + q.tail - q.head) % q.capacity + size := (q.capacity + q.rear - q.front) % q.capacity return size } // IsEmpty 判断队列是否为空 func (q *ArrayQueue) IsEmpty() bool { - return q.tail-q.head == 0 + return q.rear-q.front == 0 } // Offer 入队 -func (q *ArrayQueue) Offer(v any) { - // 当 tail == capacity 表示队列已满 +func (q *ArrayQueue) Offer(v int) { + // 当 rear == capacity 表示队列已满 if q.Size() == q.capacity { return } // 尾结点后添加 - q.data[q.tail] = v + q.data[q.rear] = v // 尾指针向后移动一位,越过尾部后返回到数组头部 - q.tail = (q.tail + 1) % q.capacity + q.rear = (q.rear + 1) % q.capacity } // Poll 出队 @@ -55,9 +50,9 @@ func (q *ArrayQueue) Poll() any { if q.IsEmpty() { return nil } - v := q.data[q.head] + v := q.data[q.front] // 队头指针向后移动一位,若越过尾部则返回到数组头部 - q.head = (q.head + 1) % q.capacity + q.front = (q.front + 1) % q.capacity return v } @@ -66,27 +61,11 @@ func (q *ArrayQueue) Peek() any { if q.IsEmpty() { return nil } - v := q.data[q.head] + v := q.data[q.front] return v } -func (q *ArrayQueue) Print() { - fmt.Println(q.toString()) -} - -// toString 通过字符串的方式输出 -func (q *ArrayQueue) toString() string { - // 为空时 - if q.IsEmpty() { - return "empty items" - } - var builder strings.Builder - size := q.Size() - str := fmt.Sprintf("%+v", q.data[q.head]) - for i := 1; i < size; i++ { - builder.WriteString(str + " -> ") - str = fmt.Sprintf("%+v", q.data[(i+q.head)%q.capacity]) - } - builder.WriteString(str) - return builder.String() +// 获取 Slice 用于打印 +func (s *ArrayQueue) toSlice() []int { + return s.data[s.front:s.rear] } diff --git a/codes/go/chapter_stack_and_queue/array_stack.go b/codes/go/chapter_stack_and_queue/array_stack.go index f3a8a287d..dca97404d 100644 --- a/codes/go/chapter_stack_and_queue/array_stack.go +++ b/codes/go/chapter_stack_and_queue/array_stack.go @@ -4,13 +4,7 @@ package chapter_stack_and_queue -import ( - "fmt" - "strconv" - "strings" -) - -// ArrayStack 基于数组实现的栈 +/* 基于数组实现的栈 */ type ArrayStack struct { data []int // 数据 } @@ -38,6 +32,7 @@ func (s *ArrayStack) Push(v int) { s.data = append(s.data, v) } +// Pop 出栈 func (s *ArrayStack) Pop() any { // 弹出栈前,先判断是否为空 if s.IsEmpty() { @@ -48,6 +43,7 @@ func (s *ArrayStack) Pop() any { return val } +// Peek 获取栈顶元素 func (s *ArrayStack) Peek() any { if s.IsEmpty() { return nil @@ -56,18 +52,7 @@ func (s *ArrayStack) Peek() any { return val } -func (s *ArrayStack) Print() { - fmt.Println(s.toString()) -} - -func (s *ArrayStack) toString() string { - var builder strings.Builder - if s.IsEmpty() { - return "empty stack" - } - for i := len(s.data) - 1; i > 0; i-- { - builder.WriteString(strconv.Itoa(s.data[i]) + " -> ") - } - builder.WriteString(strconv.Itoa(s.data[0])) - return builder.String() +// 获取 Slice 用于打印 +func (s *ArrayStack) toSlice() []int { + return s.data } diff --git a/codes/go/chapter_stack_and_queue/deque.go b/codes/go/chapter_stack_and_queue/deque.go deleted file mode 100644 index 3ac070e1a..000000000 --- a/codes/go/chapter_stack_and_queue/deque.go +++ /dev/null @@ -1,26 +0,0 @@ -// File: deque.go -// Created Time: 2022-11-29 -// Author: Reanon (793584285@qq.com) - -package chapter_stack_and_queue - -type Deque interface { - // OfferFirst 元素入队 - OfferFirst(num any) - // OfferLast 元素入队 - OfferLast(num any) - // PeekFirst 访问首元素 - PeekFirst() any - // PeekLast 访问尾元素 - PeekLast() any - // PollFirst 元素出队 - PollFirst() any - // PollLast 元素出队 - PollLast() any - // Size 获取队列长度 - Size() int - // IsEmpty 队列是否为空 - IsEmpty() bool - // toString 队列输出为字符串 - toString() string -} diff --git a/codes/go/chapter_stack_and_queue/deque_test.go b/codes/go/chapter_stack_and_queue/deque_test.go index c0eaf089e..647ac642e 100644 --- a/codes/go/chapter_stack_and_queue/deque_test.go +++ b/codes/go/chapter_stack_and_queue/deque_test.go @@ -4,12 +4,54 @@ package chapter_stack_and_queue -import "testing" +import ( + "container/list" + "fmt" + "testing" + + . "github.com/krahets/hello-algo/pkg" +) + +func TestDeque(t *testing.T) { + /* 初始化双向队列 */ + // 在 Go 中,将 list 作为双向队列使用 + deque := list.New() + + /* 元素入队 */ + deque.PushBack(2) + deque.PushBack(5) + deque.PushBack(4) + deque.PushFront(3) + deque.PushFront(1) + fmt.Print("双向队列 deque = ") + PrintList(deque) + + /* 访问元素 */ + front := deque.Front() + fmt.Println("队首元素 front =", front.Value) + rear := deque.Back() + fmt.Println("队尾元素 rear =", rear.Value) + + /* 元素出队 */ + deque.Remove(front) + fmt.Print("队首出队元素 front = ", front.Value, ",队首出队后 deque = ") + PrintList(deque) + deque.Remove(rear) + fmt.Print("队尾出队元素 rear = ", rear.Value, ",队尾出队后 deque = ") + PrintList(deque) + + /* 获取双向队列的长度 */ + size := deque.Len() + fmt.Println("双向队列长度 size =", size) + + /* 判断双向队列是否为空 */ + isEmpty := deque.Len() == 0 + fmt.Println("双向队列是否为空 =", isEmpty) +} func TestLinkedListDeque(t *testing.T) { // 初始化队列 - var deque Deque - deque = NewLinkedListDeque() + deque := NewLinkedListDeque() // 元素入队 deque.OfferLast(2) @@ -17,27 +59,30 @@ func TestLinkedListDeque(t *testing.T) { deque.OfferLast(4) deque.OfferFirst(3) deque.OfferFirst(1) - t.Log("队列 deque = ", deque.toString()) + fmt.Print("队列 deque = ") + PrintList(deque.toList()) // 访问队首元素 - peekFirst := deque.PeekFirst() - t.Log("队首元素 peek = ", peekFirst) - peekLast := deque.PeekLast() - t.Log("队尾元素 peek = ", peekLast) + front := deque.PeekFirst() + fmt.Println("队首元素 front =", front) + rear := deque.PeekLast() + fmt.Println("队尾元素 rear =", rear) // 元素出队 pollFirst := deque.PollFirst() - t.Log("队首出队元素 pollFirst = ", pollFirst, ",队首出队后 deque = ", deque.toString()) + fmt.Print("队首出队元素 pollFirst = ", pollFirst, ",队首出队后 deque = ") + PrintList(deque.toList()) pollLast := deque.PollLast() - t.Log("队尾出队元素 pollLast = ", pollLast, ",队尾出队后 deque = ", deque.toString()) + fmt.Print("队尾出队元素 pollLast = ", pollLast, ",队尾出队后 deque = ") + PrintList(deque.toList()) // 获取队的长度 size := deque.Size() - t.Log("队的长度 size = ", size) + fmt.Println("队的长度 size =", size) // 判断是否为空 isEmpty := deque.IsEmpty() - t.Log("队是否为空 = ", isEmpty) + fmt.Println("队是否为空 =", isEmpty) } // BenchmarkArrayQueue 67.92 ns/op in Mac M1 Pro diff --git a/codes/go/chapter_stack_and_queue/linkedlist_deque.go b/codes/go/chapter_stack_and_queue/linkedlist_deque.go index 62a614910..019aa778b 100644 --- a/codes/go/chapter_stack_and_queue/linkedlist_deque.go +++ b/codes/go/chapter_stack_and_queue/linkedlist_deque.go @@ -6,97 +6,79 @@ package chapter_stack_and_queue import ( "container/list" - "fmt" - "strings" ) // LinkedListDeque 基于链表实现的双端队列, 使用内置包 list 来实现栈 type LinkedListDeque struct { - list *list.List + data *list.List } // NewLinkedListDeque 初始化双端队列 func NewLinkedListDeque() *LinkedListDeque { return &LinkedListDeque{ - list: list.New(), + data: list.New(), } } -// OfferFirst 元素入队 +// OfferFirst 队首元素入队 func (s *LinkedListDeque) OfferFirst(value any) { - s.list.PushFront(value) + s.data.PushFront(value) } -// OfferLast 元素入队 +// OfferLast 队尾元素入队 func (s *LinkedListDeque) OfferLast(value any) { - s.list.PushBack(value) + s.data.PushBack(value) } -// PollFirst 元素出队 +// PollFirst 队首元素出队 func (s *LinkedListDeque) PollFirst() any { if s.IsEmpty() { return nil } - e := s.list.Front() - s.list.Remove(e) + e := s.data.Front() + s.data.Remove(e) return e.Value } -// PollLast 元素出队 +// PollLast 队尾元素出队 func (s *LinkedListDeque) PollLast() any { if s.IsEmpty() { return nil } - e := s.list.Back() - s.list.Remove(e) + e := s.data.Back() + s.data.Remove(e) return e.Value } -// PeekFirst 访问首元素 +// PeekFirst 访问队首元素 func (s *LinkedListDeque) PeekFirst() any { if s.IsEmpty() { return nil } - e := s.list.Front() + e := s.data.Front() return e.Value } -// PeekLast 访问尾元素 +// PeekLast 访问队尾元素 func (s *LinkedListDeque) PeekLast() any { if s.IsEmpty() { return nil } - e := s.list.Back() + e := s.data.Back() return e.Value } // Size 获取队列的长度 func (s *LinkedListDeque) Size() int { - return s.list.Len() + return s.data.Len() } // IsEmpty 判断队列是否为空 func (s *LinkedListDeque) IsEmpty() bool { - return s.list.Len() == 0 + return s.data.Len() == 0 } -func (s *LinkedListDeque) Print() { - fmt.Println(s.toString()) -} - -func (s *LinkedListDeque) toString() string { - var builder strings.Builder - if s.IsEmpty() { - fmt.Println("empty stack") - } - e := s.list.Front() - // 强转为 string, 会影响效率 - str := fmt.Sprintf("%v", e.Value) - for e.Next() != nil { - builder.WriteString(str + " -> ") - e = e.Next() - str = fmt.Sprintf("%v", e.Value) - } - builder.WriteString(str) - return builder.String() +// 获取 List 用于打印 +func (s *LinkedListDeque) toList() *list.List { + return s.data } diff --git a/codes/go/chapter_stack_and_queue/linkedlist_queue.go b/codes/go/chapter_stack_and_queue/linkedlist_queue.go index 5b62ac311..d30461805 100644 --- a/codes/go/chapter_stack_and_queue/linkedlist_queue.go +++ b/codes/go/chapter_stack_and_queue/linkedlist_queue.go @@ -6,25 +6,24 @@ package chapter_stack_and_queue import ( "container/list" - "fmt" - "strings" ) -// LinkedListQueue 基于链表实现的队列, 使用内置包 list 来实现栈 +/* 基于链表实现的队列 */ type LinkedListQueue struct { - list *list.List + // 使用内置包 list 来实现队列 + data *list.List } // NewLinkedListQueue 初始化链表 func NewLinkedListQueue() *LinkedListQueue { return &LinkedListQueue{ - list: list.New(), + data: list.New(), } } // Offer 入队 func (s *LinkedListQueue) Offer(value any) { - s.list.PushBack(value) + s.data.PushBack(value) } // Poll 出队 @@ -32,8 +31,8 @@ func (s *LinkedListQueue) Poll() any { if s.IsEmpty() { return nil } - e := s.list.Front() - s.list.Remove(e) + e := s.data.Front() + s.data.Remove(e) return e.Value } @@ -42,37 +41,21 @@ func (s *LinkedListQueue) Peek() any { if s.IsEmpty() { return nil } - e := s.list.Front() + e := s.data.Front() return e.Value } // Size 获取队列的长度 func (s *LinkedListQueue) Size() int { - return s.list.Len() + return s.data.Len() } // IsEmpty 判断队列是否为空 func (s *LinkedListQueue) IsEmpty() bool { - return s.list.Len() == 0 + return s.data.Len() == 0 } -func (s *LinkedListQueue) Print() { - fmt.Println(s.toString()) -} - -func (s *LinkedListQueue) toString() string { - var builder strings.Builder - if s.IsEmpty() { - fmt.Println("empty stack") - } - e := s.list.Front() - // 强转为 string, 会影响效率 - str := fmt.Sprintf("%v", e.Value) - for e.Next() != nil { - builder.WriteString(str + " -> ") - e = e.Next() - str = fmt.Sprintf("%v", e.Value) - } - builder.WriteString(str) - return builder.String() +// 获取 List 用于打印 +func (s *LinkedListQueue) toList() *list.List { + return s.data } diff --git a/codes/go/chapter_stack_and_queue/linkedlist_stack.go b/codes/go/chapter_stack_and_queue/linkedlist_stack.go index 24f46acb5..ab8a06284 100644 --- a/codes/go/chapter_stack_and_queue/linkedlist_stack.go +++ b/codes/go/chapter_stack_and_queue/linkedlist_stack.go @@ -6,25 +6,24 @@ package chapter_stack_and_queue import ( "container/list" - "fmt" - "strings" ) -// LinkedListStack 基于链表实现的栈, 使用内置包 list 来实现栈 +/* 基于链表实现的栈 */ type LinkedListStack struct { - list *list.List + // 使用内置包 list 来实现栈 + data *list.List } // NewLinkedListStack 初始化链表 func NewLinkedListStack() *LinkedListStack { return &LinkedListStack{ - list: list.New(), + data: list.New(), } } // Push 入栈 func (s *LinkedListStack) Push(value int) { - s.list.PushBack(value) + s.data.PushBack(value) } // Pop 出栈 @@ -32,8 +31,8 @@ func (s *LinkedListStack) Pop() any { if s.IsEmpty() { return nil } - e := s.list.Back() - s.list.Remove(e) + e := s.data.Back() + s.data.Remove(e) return e.Value } @@ -42,37 +41,21 @@ func (s *LinkedListStack) Peek() any { if s.IsEmpty() { return nil } - e := s.list.Back() + e := s.data.Back() return e.Value } // Size 获取栈的长度 func (s *LinkedListStack) Size() int { - return s.list.Len() + return s.data.Len() } // IsEmpty 判断栈是否为空 func (s *LinkedListStack) IsEmpty() bool { - return s.list.Len() == 0 + return s.data.Len() == 0 } -func (s *LinkedListStack) Print() { - fmt.Println(s.toString()) -} - -func (s *LinkedListStack) toString() string { - var builder strings.Builder - if s.IsEmpty() { - fmt.Println("empty stack") - } - e := s.list.Back() - // 强转为 string, 会影响效率 - str := fmt.Sprintf("%v", e.Value) - for e.Prev() != nil { - builder.WriteString(str + " -> ") - e = e.Prev() - str = fmt.Sprintf("%v", e.Value) - } - builder.WriteString(str) - return builder.String() +// 获取 List 用于打印 +func (s *LinkedListStack) toList() *list.List { + return s.data } diff --git a/codes/go/chapter_stack_and_queue/queue.go b/codes/go/chapter_stack_and_queue/queue.go deleted file mode 100644 index 03b97e5a6..000000000 --- a/codes/go/chapter_stack_and_queue/queue.go +++ /dev/null @@ -1,20 +0,0 @@ -// File: queue.go -// Created Time: 2022-11-29 -// Author: Reanon (793584285@qq.com) - -package chapter_stack_and_queue - -type Queue interface { - // Offer 元素入队 - Offer(num any) - // Peek 访问首元素 - Peek() any - // Poll 元素出队 - Poll() any - // Size 获取队列长度 - Size() int - // IsEmpty 队列是否为空 - IsEmpty() bool - // toString 队列输出为字符串 - toString() string -} diff --git a/codes/go/chapter_stack_and_queue/queue_test.go b/codes/go/chapter_stack_and_queue/queue_test.go index e8c74ecba..368becbc7 100644 --- a/codes/go/chapter_stack_and_queue/queue_test.go +++ b/codes/go/chapter_stack_and_queue/queue_test.go @@ -4,67 +4,108 @@ package chapter_stack_and_queue -import "testing" +import ( + "container/list" + "fmt" + "testing" + + . "github.com/krahets/hello-algo/pkg" +) + +func TestQueue(t *testing.T) { + /* 初始化队列 */ + // 在 Go 中,将 list 作为队列来使用 + queue := list.New() + + /* 元素入队 */ + queue.PushBack(1) + queue.PushBack(3) + queue.PushBack(2) + queue.PushBack(5) + queue.PushBack(4) + fmt.Print("队列 queue = ") + PrintList(queue) + + /* 访问队首元素 */ + peek := queue.Front() + fmt.Println("队首元素 peek =", peek.Value) + + /* 元素出队 */ + poll := queue.Front() + queue.Remove(poll) + fmt.Print("出队元素 poll = ", poll.Value, ",出队后 queue = ") + PrintList(queue) + + /* 获取队列的长度 */ + size := queue.Len() + fmt.Println("队列长度 size =", size) + + /* 判断队列是否为空 */ + isEmpty := queue.Len() == 0 + fmt.Println("队列是否为空 =", isEmpty) +} func TestArrayQueue(t *testing.T) { // 初始化队列,使用队列的通用接口 - var queue Queue capacity := 10 - queue = NewArrayQueue(capacity) + queue := NewArrayQueue(capacity) // 元素入队 queue.Offer(1) - queue.Offer(2) queue.Offer(3) - queue.Offer(4) + queue.Offer(2) queue.Offer(5) - t.Log("队列 queue = ", queue.toString()) + queue.Offer(4) + fmt.Print("队列 queue = ") + PrintSlice(queue.toSlice()) // 访问队首元素 peek := queue.Peek() - t.Log("队首元素 peek = ", peek) + fmt.Println("队首元素 peek =", peek) // 元素出队 - pop := queue.Poll() - t.Log("出队元素 pop = ", pop, ", 出队后 queue =", queue.toString()) + poll := queue.Poll() + fmt.Print("出队元素 poll = ", poll, ", 出队后 queue = ") + PrintSlice(queue.toSlice()) // 获取队的长度 size := queue.Size() - t.Log("队的长度 size = ", size) + fmt.Println("队的长度 size =", size) // 判断是否为空 isEmpty := queue.IsEmpty() - t.Log("队是否为空 = ", isEmpty) + fmt.Println("队是否为空 =", isEmpty) } func TestLinkedListQueue(t *testing.T) { // 初始化队 - var queue Queue - queue = NewLinkedListQueue() + queue := NewLinkedListQueue() // 元素入队 queue.Offer(1) - queue.Offer(2) queue.Offer(3) - queue.Offer(4) + queue.Offer(2) queue.Offer(5) - t.Log("队列 queue = ", queue.toString()) + queue.Offer(4) + fmt.Print("队列 queue = ") + PrintList(queue.toList()) // 访问队首元素 peek := queue.Peek() - t.Log("队首元素 peek = ", peek) + fmt.Println("队首元素 peek =", peek) // 元素出队 - pop := queue.Poll() - t.Log("出队元素 pop = ", pop, ", 出队后 queue =", queue.toString()) + poll := queue.Poll() + fmt.Print("出队元素 poll = ", poll, ", 出队后 queue = ") + PrintList(queue.toList()) // 获取队的长度 size := queue.Size() - t.Log("队的长度 size = ", size) + fmt.Println("队的长度 size =", size) // 判断是否为空 isEmpty := queue.IsEmpty() - t.Log("队是否为空 = ", isEmpty) + fmt.Println("队是否为空 =", isEmpty) } // BenchmarkArrayQueue 8 ns/op in Mac M1 Pro diff --git a/codes/go/chapter_stack_and_queue/stack.go b/codes/go/chapter_stack_and_queue/stack.go deleted file mode 100644 index 779538784..000000000 --- a/codes/go/chapter_stack_and_queue/stack.go +++ /dev/null @@ -1,20 +0,0 @@ -// File: stack.go -// Created Time: 2022-11-26 -// Author: Reanon (793584285@qq.com) - -package chapter_stack_and_queue - -type Stack interface { - // Push 元素入栈 - Push(num int) - // Peek 访问栈顶元素 - Peek() any - // Pop 元素出栈 - Pop() any - // Size 栈的长度 - Size() int - // IsEmpty 栈是否为空 - IsEmpty() bool - // toString 栈输出为字符串 - toString() string -} diff --git a/codes/go/chapter_stack_and_queue/stack_test.go b/codes/go/chapter_stack_and_queue/stack_test.go index 95c6d2410..9dc97e697 100644 --- a/codes/go/chapter_stack_and_queue/stack_test.go +++ b/codes/go/chapter_stack_and_queue/stack_test.go @@ -4,65 +4,105 @@ package chapter_stack_and_queue -import "testing" +import ( + "fmt" + "testing" + + . "github.com/krahets/hello-algo/pkg" +) + +func TestStack(t *testing.T) { + /* 初始化栈 */ + // 在 Go 中,推荐将 Slice 当作栈来使用 + var stack []int + + /* 元素入栈 */ + stack = append(stack, 1) + stack = append(stack, 3) + stack = append(stack, 2) + stack = append(stack, 5) + stack = append(stack, 4) + fmt.Print("栈 = ") + PrintSlice(stack) + + /* 访问栈顶元素 */ + peek := stack[len(stack)-1] + fmt.Println("栈顶元素 peek =", peek) + + /* 元素出栈 */ + pop := stack[len(stack)-1] + stack = stack[:len(stack)-1] + fmt.Print("出栈元素 pop = ", pop, ",出栈后 stack = ") + PrintSlice(stack) + + /* 获取栈的长度 */ + size := len(stack) + fmt.Println("栈的长度 size =", size) + + /* 判断是否为空 */ + isEmpty := len(stack) == 0 + fmt.Println("栈是否为空 =", isEmpty) +} func TestArrayStack(t *testing.T) { // 初始化栈, 使用接口承接 - var stack Stack - stack = NewArrayStack() + stack := NewArrayStack() // 元素入栈 stack.Push(1) - stack.Push(2) stack.Push(3) - stack.Push(4) + stack.Push(2) stack.Push(5) - t.Log("栈 stack = ", stack.toString()) + stack.Push(4) + fmt.Print("栈 stack = ") + PrintSlice(stack.toSlice()) // 访问栈顶元素 peek := stack.Peek() - t.Log("栈顶元素 peek = ", peek) + fmt.Println("栈顶元素 peek =", peek) // 元素出栈 pop := stack.Pop() - t.Log("出栈元素 pop = ", pop, ", 出栈后 stack =", stack.toString()) + fmt.Print("出栈元素 pop = ", pop, ", 出栈后 stack = ") + PrintSlice(stack.toSlice()) // 获取栈的长度 size := stack.Size() - t.Log("栈的长度 size = ", size) + fmt.Println("栈的长度 size =", size) // 判断是否为空 isEmpty := stack.IsEmpty() - t.Log("栈是否为空 = ", isEmpty) + fmt.Println("栈是否为空 =", isEmpty) } func TestLinkedListStack(t *testing.T) { // 初始化栈 - var stack Stack - stack = NewLinkedListStack() + stack := NewLinkedListStack() // 元素入栈 stack.Push(1) - stack.Push(2) stack.Push(3) - stack.Push(4) + stack.Push(2) stack.Push(5) - t.Log("栈 stack = ", stack.toString()) + stack.Push(4) + fmt.Print("栈 stack = ") + PrintList(stack.toList()) // 访问栈顶元素 peek := stack.Peek() - t.Log("栈顶元素 peek = ", peek) + fmt.Println("栈顶元素 peek =", peek) // 元素出栈 pop := stack.Pop() - t.Log("出栈元素 pop = ", pop, ", 出栈后 stack =", stack.toString()) + fmt.Print("出栈元素 pop = ", pop, ", 出栈后 stack = ") + PrintList(stack.toList()) // 获取栈的长度 size := stack.Size() - t.Log("栈的长度 size = ", size) + fmt.Println("栈的长度 size =", size) // 判断是否为空 isEmpty := stack.IsEmpty() - t.Log("栈是否为空 = ", isEmpty) + fmt.Println("栈是否为空 =", isEmpty) } // BenchmarkArrayStack 8 ns/op in Mac M1 Pro diff --git a/codes/go/chapter_tree/binary_search_tree.go b/codes/go/chapter_tree/binary_search_tree.go index ac14e798d..2af2e7be0 100644 --- a/codes/go/chapter_tree/binary_search_tree.go +++ b/codes/go/chapter_tree/binary_search_tree.go @@ -53,7 +53,7 @@ func (bst *BinarySearchTree) GetInorderNext(node *TreeNode) *TreeNode { return node } -// Search node of binary search tree +/* 查找结点 */ func (bst *BinarySearchTree) Search(num int) *TreeNode { node := bst.root // 循环查找,越过叶结点后跳出 @@ -73,7 +73,7 @@ func (bst *BinarySearchTree) Search(num int) *TreeNode { return node } -// Insert node of binary search tree +/* 插入结点 */ func (bst *BinarySearchTree) Insert(num int) *TreeNode { cur := bst.root // 若树为空,直接提前返回 @@ -104,7 +104,7 @@ func (bst *BinarySearchTree) Insert(num int) *TreeNode { return cur } -// Remove node of binary search tree +/* 删除结点 */ func (bst *BinarySearchTree) Remove(num int) *TreeNode { cur := bst.root // 若树为空,直接提前返回 @@ -119,8 +119,8 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode { break } prev = cur - // 待删除结点在右子树中 if cur.Val < num { + // 待删除结点在右子树中 cur = cur.Right } else { // 待删除结点在左子树中 @@ -146,8 +146,8 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode { } else { prev.Right = child } - - } else { // 子结点数为 2 + // 子结点数为 2 + } else { // 获取中序遍历中待删除结点 cur 的下一个结点 next := bst.GetInorderNext(cur) temp := next.Val @@ -156,7 +156,6 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode { // 将 next 的值复制给 cur cur.Val = temp } - // TODO: add error handler, don't return node return cur } diff --git a/codes/go/chapter_tree/binary_search_tree_test.go b/codes/go/chapter_tree/binary_search_tree_test.go index 5ae932b07..0d0369a78 100644 --- a/codes/go/chapter_tree/binary_search_tree_test.go +++ b/codes/go/chapter_tree/binary_search_tree_test.go @@ -4,38 +4,41 @@ package chapter_tree -import "testing" +import ( + "fmt" + "testing" +) func TestBinarySearchTree(t *testing.T) { nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} bst := NewBinarySearchTree(nums) - t.Log("初始化的二叉树为:") + fmt.Println("初始化的二叉树为:") bst.Print() // 获取根结点 node := bst.GetRoot() - t.Log("二叉树的根结点为:", node.Val) + fmt.Println("二叉树的根结点为:", node.Val) // 获取最小的结点 node = bst.GetMin(bst.GetRoot()) - t.Log("二叉树的最小结点为:", node.Val) + fmt.Println("二叉树的最小结点为:", node.Val) // 查找结点 node = bst.Search(5) - t.Log("查找到的结点对象为", node, ",结点值 =", node.Val) + fmt.Println("查找到的结点对象为", node, ",结点值 =", node.Val) // 插入结点 node = bst.Insert(16) - t.Log("插入结点后 16 的二叉树为:") + fmt.Println("插入结点后 16 的二叉树为:") bst.Print() // 删除结点 bst.Remove(1) - t.Log("删除结点 1 后的二叉树为:") + fmt.Println("删除结点 1 后的二叉树为:") bst.Print() bst.Remove(2) - t.Log("删除结点 2 后的二叉树为:") + fmt.Println("删除结点 2 后的二叉树为:") bst.Print() bst.Remove(4) - t.Log("删除结点 4 后的二叉树为:") + fmt.Println("删除结点 4 后的二叉树为:") bst.Print() } diff --git a/codes/go/chapter_tree/binary_tree.go b/codes/go/chapter_tree/binary_tree.go deleted file mode 100644 index 72143cd9a..000000000 --- a/codes/go/chapter_tree/binary_tree.go +++ /dev/null @@ -1,23 +0,0 @@ -// File: binary_tree.go -// Created Time: 2022-11-25 -// Author: Reanon (793584285@qq.com) - -package chapter_tree - -import ( - . "github.com/krahets/hello-algo/pkg" -) - -type BinaryTree struct { - root *TreeNode -} - -func NewBinaryTree(node *TreeNode) *BinaryTree { - return &BinaryTree{ - root: node, - } -} - -func (tree *BinaryTree) Print() { - PrintTree(tree.root) -} diff --git a/codes/go/chapter_tree/binary_tree_bfs.go b/codes/go/chapter_tree/binary_tree_bfs.go index 5c07a96bc..d77bc97b1 100644 --- a/codes/go/chapter_tree/binary_tree_bfs.go +++ b/codes/go/chapter_tree/binary_tree_bfs.go @@ -10,11 +10,10 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -// levelOrder Breadth First Search +/* 层序遍历 */ func levelOrder(root *TreeNode) []int { - // Let container.list as queue - queue := list.New() // 初始化队列,加入根结点 + queue := list.New() queue.PushBack(root) // 初始化一个切片,用于保存遍历序列 nums := make([]int, 0) diff --git a/codes/go/chapter_tree/binary_tree_bfs_test.go b/codes/go/chapter_tree/binary_tree_bfs_test.go index c06cd9e77..8d5c0aaff 100644 --- a/codes/go/chapter_tree/binary_tree_bfs_test.go +++ b/codes/go/chapter_tree/binary_tree_bfs_test.go @@ -5,6 +5,7 @@ package chapter_tree import ( + "fmt" "testing" . "github.com/krahets/hello-algo/pkg" @@ -14,10 +15,10 @@ func TestLevelOrder(t *testing.T) { /* 初始化二叉树 */ // 这里借助了一个从数组直接生成二叉树的函数 root := ArrayToTree([]int{1, 2, 3, 4, 5, 6, 7}) - t.Log("初始化二叉树: ") + fmt.Println("初始化二叉树: ") PrintTree(root) // 层序遍历 nums := levelOrder(root) - t.Log("层序遍历的结点打印序列 =", nums) + fmt.Println("层序遍历的结点打印序列 =", nums) } diff --git a/codes/go/chapter_tree/binary_tree_dfs.go b/codes/go/chapter_tree/binary_tree_dfs.go index c97aa17df..1a857ebae 100644 --- a/codes/go/chapter_tree/binary_tree_dfs.go +++ b/codes/go/chapter_tree/binary_tree_dfs.go @@ -8,56 +8,37 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -// preOrder 前序遍历 -func preOrder(root *TreeNode) (nums []int) { - var preOrderHelper func(node *TreeNode) - // 匿名函数 - preOrderHelper = func(node *TreeNode) { - if node == nil { - return - } - // 访问优先级:根结点 -> 左子树 -> 右子树 - nums = append(nums, node.Val) - preOrderHelper(node.Left) - preOrderHelper(node.Right) +var nums []int + +/* 前序遍历 */ +func preOrder(node *TreeNode) { + if node == nil { + return } - // 函数调用 - preOrderHelper(root) - return + // 访问优先级:根结点 -> 左子树 -> 右子树 + nums = append(nums, node.Val) + preOrder(node.Left) + preOrder(node.Right) } -// inOrder 中序遍历 -func inOrder(root *TreeNode) (nums []int) { - var inOrderHelper func(node *TreeNode) - // 匿名函数 - inOrderHelper = func(node *TreeNode) { - if node == nil { - return - } - // 访问优先级:左子树 -> 根结点 -> 右子树 - inOrderHelper(node.Left) - nums = append(nums, node.Val) - inOrderHelper(node.Right) +/* 中序遍历 */ +func inOrder(node *TreeNode) { + if node == nil { + return } - // 函数调用 - inOrderHelper(root) - return + // 访问优先级:左子树 -> 根结点 -> 右子树 + inOrder(node.Left) + nums = append(nums, node.Val) + inOrder(node.Right) } -// postOrder 后序遍历 -func postOrder(root *TreeNode) (nums []int) { - var postOrderHelper func(node *TreeNode) - // 匿名函数 - postOrderHelper = func(node *TreeNode) { - if node == nil { - return - } - // 访问优先级:左子树 -> 右子树 -> 根结点 - postOrderHelper(node.Left) - postOrderHelper(node.Right) - nums = append(nums, node.Val) +/* 后序遍历 */ +func postOrder(node *TreeNode) { + if node == nil { + return } - // 函数调用 - postOrderHelper(root) - return + // 访问优先级:左子树 -> 右子树 -> 根结点 + postOrder(node.Left) + postOrder(node.Right) + nums = append(nums, node.Val) } diff --git a/codes/go/chapter_tree/binary_tree_dfs_test.go b/codes/go/chapter_tree/binary_tree_dfs_test.go index 2ee6295f6..67a3e1f3a 100644 --- a/codes/go/chapter_tree/binary_tree_dfs_test.go +++ b/codes/go/chapter_tree/binary_tree_dfs_test.go @@ -5,6 +5,7 @@ package chapter_tree import ( + "fmt" "testing" . "github.com/krahets/hello-algo/pkg" @@ -14,18 +15,21 @@ func TestPreInPostOrderTraversal(t *testing.T) { /* 初始化二叉树 */ // 这里借助了一个从数组直接生成二叉树的函数 root := ArrayToTree([]int{1, 2, 3, 4, 5, 6, 7}) - t.Log("初始化二叉树: ") + fmt.Println("初始化二叉树: ") PrintTree(root) // 前序遍历 - nums := preOrder(root) - t.Log("前序遍历的结点打印序列 =", nums) + nums = nil + preOrder(root) + fmt.Println("前序遍历的结点打印序列 =", nums) // 中序遍历 - nums = inOrder(root) - t.Log("中序遍历的结点打印序列 =", nums) + nums = nil + inOrder(root) + fmt.Println("中序遍历的结点打印序列 =", nums) // 后序遍历 - nums = postOrder(root) - t.Log("后序遍历的结点打印序列 =", nums) + nums = nil + postOrder(root) + fmt.Println("后序遍历的结点打印序列 =", nums) } diff --git a/codes/go/chapter_tree/binary_tree_test.go b/codes/go/chapter_tree/binary_tree_test.go index 03a85539a..f91e816fb 100644 --- a/codes/go/chapter_tree/binary_tree_test.go +++ b/codes/go/chapter_tree/binary_tree_test.go @@ -5,6 +5,7 @@ package chapter_tree import ( + "fmt" "testing" . "github.com/krahets/hello-algo/pkg" @@ -18,24 +19,23 @@ func TestBinaryTree(t *testing.T) { n3 := NewTreeNode(3) n4 := NewTreeNode(4) n5 := NewTreeNode(5) - - tree := NewBinaryTree(n1) + // 构建引用指向(即指针) n1.Left = n2 n1.Right = n3 n2.Left = n4 n2.Right = n5 - t.Log("初始化二叉树") - tree.Print() + fmt.Println("初始化二叉树") + PrintTree(n1) /* 插入与删除结点 */ + // 插入结点 p := NewTreeNode(0) n1.Left = p p.Left = n2 - t.Log("插入结点 P 后") - tree.Print() - + fmt.Println("插入结点 P 后") + PrintTree(n1) // 删除结点 n1.Left = n2 - t.Log("删除结点 P 后") - tree.Print() + fmt.Println("删除结点 P 后") + PrintTree(n1) } diff --git a/codes/go/pkg/list_node.go b/codes/go/pkg/list_node.go index 6795111ea..f1c152de1 100644 --- a/codes/go/pkg/list_node.go +++ b/codes/go/pkg/list_node.go @@ -4,12 +4,6 @@ package pkg -import ( - "fmt" - "strconv" - "strings" -) - // ListNode Definition for a singly-linked list node type ListNode struct { Next *ListNode @@ -43,17 +37,3 @@ func GetListNode(node *ListNode, val int) *ListNode { } return node } - -// PrintLinkedList Print a linked list -func PrintLinkedList(node *ListNode) { - if node == nil { - return - } - var builder strings.Builder - for node.Next != nil { - builder.WriteString(strconv.Itoa(node.Val) + " -> ") - node = node.Next - } - builder.WriteString(strconv.Itoa(node.Val)) - fmt.Println(builder.String()) -} diff --git a/codes/go/pkg/list_node_test.go b/codes/go/pkg/list_node_test.go index 5bc33d99d..31b99618f 100644 --- a/codes/go/pkg/list_node_test.go +++ b/codes/go/pkg/list_node_test.go @@ -4,7 +4,10 @@ package pkg -import "testing" +import ( + "fmt" + "testing" +) func TestListNode(t *testing.T) { arr := []int{2, 3, 5, 6, 7} @@ -12,5 +15,5 @@ func TestListNode(t *testing.T) { PrintLinkedList(head) node := GetListNode(head, 5) - t.Log("Find node: ", node.Val) + fmt.Println("Find node: ", node.Val) } diff --git a/codes/go/pkg/print_utils.go b/codes/go/pkg/print_utils.go new file mode 100644 index 000000000..e42d40684 --- /dev/null +++ b/codes/go/pkg/print_utils.go @@ -0,0 +1,98 @@ +// File: print_utils.go +// Created Time: 2022-12-03 +// Author: Reanon (793584285@qq.com), Krahets (krahets@163.com) + +package pkg + +import ( + "container/list" + "fmt" + "strconv" + "strings" +) + +func PrintSlice(nums []int) { + fmt.Printf("%v", nums) + fmt.Println() +} + +// PrintList Print a list +func PrintList(list *list.List) { + e := list.Front() + // 强转为 string, 会影响效率 + fmt.Print("[") + for e.Next() != nil { + fmt.Print(e.Value, " ") + e = e.Next() + } + fmt.Print(e.Value, "]\n") +} + +// PrintLinkedList Print a linked list +func PrintLinkedList(node *ListNode) { + if node == nil { + return + } + var builder strings.Builder + for node.Next != nil { + builder.WriteString(strconv.Itoa(node.Val) + " -> ") + node = node.Next + } + builder.WriteString(strconv.Itoa(node.Val)) + fmt.Println(builder.String()) +} + +// PrintTree Print a binary tree +func PrintTree(root *TreeNode) { + printTreeHelper(root, nil, false) +} + +// printTreeHelper Help to print a binary tree, hide more details +// This tree printer is borrowed from TECHIE DELIGHT +// https://www.techiedelight.com/c-program-print-binary-tree/ +func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) { + if root == nil { + return + } + prevStr := " " + trunk := newTrunk(prev, prevStr) + printTreeHelper(root.Right, trunk, true) + if prev == nil { + trunk.str = "———" + } else if isLeft { + trunk.str = "/———" + prevStr = " |" + } else { + trunk.str = "\\———" + prev.str = prevStr + } + showTrunk(trunk) + fmt.Println(root.Val) + if prev != nil { + prev.str = prevStr + } + trunk.str = " |" + printTreeHelper(root.Left, trunk, false) +} + +// trunk Help to Print tree structure +type trunk struct { + prev *trunk + str string +} + +func newTrunk(prev *trunk, str string) *trunk { + return &trunk{ + prev: prev, + str: str, + } +} + +func showTrunk(t *trunk) { + if t == nil { + return + } + + showTrunk(t.prev) + fmt.Print(t.str) +} diff --git a/codes/go/pkg/tree_node.go b/codes/go/pkg/tree_node.go index b62dc6056..2511a7655 100644 --- a/codes/go/pkg/tree_node.go +++ b/codes/go/pkg/tree_node.go @@ -6,7 +6,6 @@ package pkg import ( "container/list" - "fmt" ) type TreeNode struct { @@ -71,58 +70,3 @@ func TreeToArray(root *TreeNode) []any { } return arr } - -// PrintTree Print a binary tree -func PrintTree(root *TreeNode) { - printTreeHelper(root, nil, false) -} - -// printTreeHelper Help to print a binary tree, hide more details -// This tree printer is borrowed from TECHIE DELIGHT -// https://www.techiedelight.com/c-program-print-binary-tree/ -func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) { - if root == nil { - return - } - prevStr := " " - trunk := newTrunk(prev, prevStr) - printTreeHelper(root.Right, trunk, true) - if prev == nil { - trunk.str = "———" - } else if isLeft { - trunk.str = "/———" - prevStr = " |" - } else { - trunk.str = "\\———" - prev.str = prevStr - } - showTrunk(trunk) - fmt.Println(root.Val) - if prev != nil { - prev.str = prevStr - } - trunk.str = " |" - printTreeHelper(root.Left, trunk, false) -} - -// trunk Help to Print tree structure -type trunk struct { - prev *trunk - str string -} - -func newTrunk(prev *trunk, str string) *trunk { - return &trunk{ - prev: prev, - str: str, - } -} - -func showTrunk(t *trunk) { - if t == nil { - return - } - - showTrunk(t.prev) - fmt.Print(t.str) -} diff --git a/codes/go/pkg/tree_node_test.go b/codes/go/pkg/tree_node_test.go index ffbdf6ff0..b4c8e0773 100644 --- a/codes/go/pkg/tree_node_test.go +++ b/codes/go/pkg/tree_node_test.go @@ -4,7 +4,10 @@ package pkg -import "testing" +import ( + "fmt" + "testing" +) func TestTreeNode(t *testing.T) { arr := []int{2, 3, 5, 6, 7} @@ -14,5 +17,5 @@ func TestTreeNode(t *testing.T) { PrintTree(node) // tree to arr - t.Log(TreeToArray(node)) + fmt.Println(TreeToArray(node)) } diff --git a/codes/java/chapter_stack_and_queue/deque.java b/codes/java/chapter_stack_and_queue/deque.java index cdfe65bf7..a29e6e7c3 100644 --- a/codes/java/chapter_stack_and_queue/deque.java +++ b/codes/java/chapter_stack_and_queue/deque.java @@ -21,7 +21,7 @@ public class deque { deque.offerFirst(1); System.out.println("双向队列 deque = " + deque); - /* 访问队首元素 */ + /* 访问元素 */ int peekFirst = deque.peekFirst(); System.out.println("队首元素 peekFirst = " + peekFirst); int peekLast = deque.peekLast(); diff --git a/codes/javascript/chapter_array_and_linkedlist/array.js b/codes/javascript/chapter_array_and_linkedlist/array.js index a8294cc24..4cf1b29fa 100644 --- a/codes/javascript/chapter_array_and_linkedlist/array.js +++ b/codes/javascript/chapter_array_and_linkedlist/array.js @@ -7,7 +7,7 @@ /* 随机访问元素 */ function randomAccess(nums){ // 在区间 [0, nums.length) 中随机抽取一个数字 - const random_index = Math.floor(Math.random() * nums.length) + const random_index = Math.floor(Math.random() * nums.length) // 获取并返回随机元素 random_num = nums[random_index] return random_num diff --git a/codes/javascript/chapter_sorting/insertion_sort.js b/codes/javascript/chapter_sorting/insertion_sort.js index 9a6f119ba..02c45a237 100644 --- a/codes/javascript/chapter_sorting/insertion_sort.js +++ b/codes/javascript/chapter_sorting/insertion_sort.js @@ -21,4 +21,4 @@ function insertionSort(nums) { /* Driver Code */ var nums = [4, 1, 3, 1, 5, 2] insertionSort(nums) -console.log("排序后数组 nums = ", nums) +console.log("排序后数组 nums =", nums) diff --git a/codes/python/chapter_array_and_linkedlist/list.py b/codes/python/chapter_array_and_linkedlist/list.py index 4cd9b0312..ac71b98b8 100644 --- a/codes/python/chapter_array_and_linkedlist/list.py +++ b/codes/python/chapter_array_and_linkedlist/list.py @@ -33,7 +33,7 @@ if __name__ == "__main__": list.append(2) list.append(5) list.append(4) - print("添加元素后 list = ", list) + print("添加元素后 list =", list) """ 中间插入元素 """ list.insert(3, 6) diff --git a/codes/python/chapter_searching/binary_search.py b/codes/python/chapter_searching/binary_search.py index 709a2b698..3d9ee0ffc 100644 --- a/codes/python/chapter_searching/binary_search.py +++ b/codes/python/chapter_searching/binary_search.py @@ -1,10 +1,53 @@ ''' File: binary_search.py -Created Time: 2022-11-25 -Author: Krahets (krahets@163.com) +Created Time: 2022-11-26 +Author: timi (xisunyy@163.com) ''' import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from include import * +""" 二分查找(双闭区间) """ +def binary_search(nums, target): + # 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素 + i, j = 0, len(nums) - 1 + while i <= j: + m = (i + j) // 2 # 计算中点索引 m + if nums[m] < target: # 此情况说明 target 在区间 [m+1, j] 中 + i = m + 1 + elif nums[m] > target: # 此情况说明 target 在区间 [i, m-1] 中 + j = m - 1 + else: + return m # 找到目标元素,返回其索引 + return -1 # 未找到目标元素,返回 -1 + + +""" 二分查找(左闭右开) """ +def binary_search1(nums, target): + # 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1 + i, j = 0, len(nums) + # 循环,当搜索区间为空时跳出(当 i = j 时为空) + while i < j: + m = (i + j) // 2 # 计算中点索引 m + if nums[m] < target: # 此情况说明 target 在区间 [m+1, j) 中 + i = m + 1 + elif nums[m] > target: # 此情况说明 target 在区间 [i, m) 中 + j = m + else: # 找到目标元素,返回其索引 + return m + return -1 # 未找到目标元素,返回 -1 + + +""" Driver Code """ +if __name__ == '__main__': + target = 6 + nums = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92] + + # 二分查找(双闭区间) + index = binary_search(nums, target) + print("目标元素 6 的索引 = ", index) + + # 二分查找(左闭右开) + index = binary_search1(nums, target) + print("目标元素 6 的索引 = ", index) diff --git a/codes/python/chapter_searching/hashing_search.py b/codes/python/chapter_searching/hashing_search.py index 90de74f22..68cffe64a 100644 --- a/codes/python/chapter_searching/hashing_search.py +++ b/codes/python/chapter_searching/hashing_search.py @@ -1,10 +1,45 @@ ''' File: hashing_search.py -Created Time: 2022-11-25 -Author: Krahets (krahets@163.com) +Created Time: 2022-11-26 +Author: timi (xisunyy@163.com) ''' import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from include import * +""" 哈希查找(数组) """ +def hashing_search(mapp, target): + # 哈希表的 key: 目标元素,value: 索引 + # 若哈希表中无此 key ,返回 -1 + return mapp.get(target, -1) + +""" 哈希查找(链表) """ +def hashing_search1(mapp, target): + # 哈希表的 key: 目标元素,value: 结点对象 + # 若哈希表中无此 key ,返回 -1 + return mapp.get(target, -1) + + +""" Driver Code """ +if __name__ == '__main__': + target = 3 + + # 哈希查找(数组) + nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8] + # 初始化哈希表 + mapp = {} + for i in range(len(nums)): + mapp[nums[i]] = i # key: 元素,value: 索引 + index = hashing_search(mapp, target) + print("目标元素 3 的索引 =", index) + + # 哈希查找(链表) + head = list_to_linked_list(nums) + # 初始化哈希表 + map1 = {} + while head: + map1[head.val] = head # key: 结点值,value: 结点 + head = head.next + node = hashing_search1(map1, target) + print("目标结点值 3 的对应结点对象为", node) diff --git a/codes/python/chapter_searching/linear_search.py b/codes/python/chapter_searching/linear_search.py index 961e75fb0..933095653 100644 --- a/codes/python/chapter_searching/linear_search.py +++ b/codes/python/chapter_searching/linear_search.py @@ -1,10 +1,41 @@ ''' File: linear_search.py -Created Time: 2022-11-25 -Author: Krahets (krahets@163.com) +Created Time: 2022-11-26 +Author: timi (xisunyy@163.com) ''' import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from include import * +""" 线性查找(数组) """ +def linear_search(nums, target): + # 遍历数组 + for i in range(len(nums)): + if nums[i] == target: # 找到目标元素,返回其索引 + return i + return -1 # 未找到目标元素,返回 -1 + +""" 线性查找(链表) """ +def linear_search1(head, target): + # 遍历链表 + while head: + if head.val == target: # 找到目标结点,返回之 + return head + head = head.next + return None # 未找到目标结点,返回 None + + +""" Driver Code """ +if __name__ == '__main__': + target = 3 + + # 在数组中执行线性查找 + nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8] + index = linear_search(nums, target) + print("目标元素 3 的索引 =", index) + + # 在链表中执行线性查找 + head = list_to_linked_list(nums) + node = linear_search1(head, target) + print("目标结点值 3 的对应结点对象为", node) diff --git a/codes/python/chapter_sorting/insertion_sort.py b/codes/python/chapter_sorting/insertion_sort.py index 9f3267388..db85515d1 100644 --- a/codes/python/chapter_sorting/insertion_sort.py +++ b/codes/python/chapter_sorting/insertion_sort.py @@ -25,4 +25,4 @@ def insertion_sort(nums): if __name__ == '__main__': nums = [4, 1, 3, 1, 5, 2] insertion_sort(nums) - print("排序后数组 nums = ", nums) + print("排序后数组 nums =", nums) diff --git a/codes/python/chapter_stack_and_queue/deque.py b/codes/python/chapter_stack_and_queue/deque.py index 8a68fe76f..7881a965e 100644 --- a/codes/python/chapter_stack_and_queue/deque.py +++ b/codes/python/chapter_stack_and_queue/deque.py @@ -26,7 +26,7 @@ if __name__ == "__main__": duque.appendleft(1) print("双向队列 duque =", duque) - """ 访问队首元素 """ + """ 访问元素 """ front = duque[0] # 队首元素 print("队首元素 front =", front) rear = duque[-1] # 队尾元素 diff --git a/docs/chapter_array_and_linkedlist/array.md b/docs/chapter_array_and_linkedlist/array.md index 74e2063f0..fcd7e450b 100644 --- a/docs/chapter_array_and_linkedlist/array.md +++ b/docs/chapter_array_and_linkedlist/array.md @@ -138,7 +138,7 @@ elementAddr = firtstElementAddr + elementLength * elementIndex /* 随机返回一个数组元素 */ function randomAccess(nums){ // 在区间 [0, nums.length) 中随机抽取一个数字 - const random_index = Math.floor(Math.random() * nums.length) + const random_index = Math.floor(Math.random() * nums.length) // 获取并返回随机元素 random_num = nums[random_index] return random_num diff --git a/docs/chapter_computational_complexity/space_complexity.md b/docs/chapter_computational_complexity/space_complexity.md index eda90137c..ac2c9df48 100644 --- a/docs/chapter_computational_complexity/space_complexity.md +++ b/docs/chapter_computational_complexity/space_complexity.md @@ -520,7 +520,7 @@ $$ ```python title="space_complexity_types.py" """ 线性阶(递归实现) """ def linearRecur(n): - print("递归 n = ", n) + print("递归 n =", n) if n == 1: return linearRecur(n - 1) ``` diff --git a/docs/chapter_computational_complexity/time_complexity.md b/docs/chapter_computational_complexity/time_complexity.md index 555525207..9ee13d8db 100644 --- a/docs/chapter_computational_complexity/time_complexity.md +++ b/docs/chapter_computational_complexity/time_complexity.md @@ -15,7 +15,7 @@ comments: true 例如以下代码,输入数据大小为 $n$ ,根据以上方法,可以得到算法运行时间为 $6n + 12$ ns 。 $$ -1 + 1 + 10 + (1 + 5) \times n = 6n + 12 +1 + 1 + 10 + (1 + 5) \times n = 6n + 12 $$ === "Java" diff --git a/docs/chapter_searching/binary_search.md b/docs/chapter_searching/binary_search.md index bd3b109b0..1333faf0f 100644 --- a/docs/chapter_searching/binary_search.md +++ b/docs/chapter_searching/binary_search.md @@ -105,7 +105,19 @@ $$ === "Python" ```python title="binary_search.py" - + """ 二分查找(双闭区间) """ + def binary_search(nums, target): + # 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素 + i, j = 0, len(nums) - 1 + while i <= j: + m = (i + j) // 2 # 计算中点索引 m + if nums[m] < target: # 此情况说明 target 在区间 [m+1, j] 中 + i = m + 1 + elif nums[m] > target: # 此情况说明 target 在区间 [i, m-1] 中 + j = m - 1 + else: + return m # 找到目标元素,返回其索引 + return -1 # 未找到目标元素,返回 -1 ``` === "Go" @@ -189,7 +201,20 @@ $$ === "Python" ```python title="binary_search.py" - + """ 二分查找(左闭右开) """ + def binary_search1(nums, target): + # 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1 + i, j = 0, len(nums) + # 循环,当搜索区间为空时跳出(当 i = j 时为空) + while i < j: + m = (i + j) // 2 # 计算中点索引 m + if nums[m] < target: # 此情况说明 target 在区间 [m+1, j) 中 + i = m + 1 + elif nums[m] > target: # 此情况说明 target 在区间 [i, m) 中 + j = m + else: # 找到目标元素,返回其索引 + return m + return -1 # 未找到目标元素,返回 -1 ``` === "Go" @@ -262,8 +287,8 @@ $$ === "Python" ```py title="" - # Python 中的数字理论上可以无限大(取决于内存) - # 因此无需考虑大数越界问题 + # Python 中的数字理论上可以无限大(取决于内存大小) + # 因此无需考虑大数越界问题 ``` === "Go" diff --git a/docs/chapter_searching/hashing_search.md b/docs/chapter_searching/hashing_search.md index f269c4efa..d00fc21bd 100644 --- a/docs/chapter_searching/hashing_search.md +++ b/docs/chapter_searching/hashing_search.md @@ -43,7 +43,11 @@ comments: true === "Python" ```python title="hashing_search.py" - + """ 哈希查找(数组) """ + def hashing_search(mapp, target): + # 哈希表的 key: 目标元素,value: 索引 + # 若哈希表中无此 key ,返回 -1 + return mapp.get(target, -1) ``` === "Go" @@ -107,7 +111,11 @@ comments: true === "Python" ```python title="hashing_search.py" - + """ 哈希查找(链表) """ + def hashing_search1(mapp, target): + # 哈希表的 key: 目标元素,value: 结点对象 + # 若哈希表中无此 key ,返回 -1 + return mapp.get(target, -1) ``` === "Go" diff --git a/docs/chapter_searching/linear_search.md b/docs/chapter_searching/linear_search.md index ba3024875..e635c7d0e 100644 --- a/docs/chapter_searching/linear_search.md +++ b/docs/chapter_searching/linear_search.md @@ -47,7 +47,13 @@ comments: true === "Python" ```python title="linear_search.py" - + """ 线性查找(数组) """ + def linear_search(nums, target): + # 遍历数组 + for i in range(len(nums)): + if nums[i] == target: # 找到目标元素,返回其索引 + return i + return -1 # 未找到目标元素,返回 -1 ``` === "Go" @@ -119,7 +125,14 @@ comments: true === "Python" ```python title="linear_search.py" - + """ 线性查找(链表) """ + def linear_search1(head, target): + # 遍历链表 + while head: + if head.val == target: # 找到目标结点,返回之 + return head + head = head.next + return None # 未找到目标结点,返回 None ``` === "Go" diff --git a/docs/chapter_stack_and_queue/deque.md b/docs/chapter_stack_and_queue/deque.md index 2ed2f289a..c764ca68b 100644 --- a/docs/chapter_stack_and_queue/deque.md +++ b/docs/chapter_stack_and_queue/deque.md @@ -46,7 +46,7 @@ comments: true deque.offerFirst(3); // 添加至队首 deque.offerFirst(1); - /* 访问队首元素 */ + /* 访问元素 */ int peekFirst = deque.peekFirst(); // 队首元素 int peekLast = deque.peekLast(); // 队尾元素 @@ -74,7 +74,7 @@ comments: true deque.push_front(3); // 添加至队首 deque.push_front(1); - /* 访问队首元素 */ + /* 访问元素 */ int front = deque.front(); // 队首元素 int back = deque.back(); // 队尾元素 @@ -102,7 +102,7 @@ comments: true duque.appendleft(3) # 添加至队首 duque.appendleft(1) - """ 访问队首元素 """ + """ 访问元素 """ front = duque[0] # 队首元素 rear = duque[-1] # 队尾元素 @@ -120,7 +120,30 @@ comments: true === "Go" ```go title="deque.go" + /* 初始化双向队列 */ + // 在 Go 中,将 list 作为双向队列使用 + deque := list.New() + /* 元素入队 */ + deque.PushBack(2) // 添加至队尾 + deque.PushBack(5) + deque.PushBack(4) + deque.PushFront(3) // 添加至队首 + deque.PushFront(1) + + /* 访问元素 */ + front := deque.Front() // 队首元素 + rear := deque.Back() // 队尾元素 + + /* 元素出队 */ + deque.Remove(front) // 队首元素出队 + deque.Remove(rear) // 队尾元素出队 + + /* 获取双向队列的长度 */ + size := deque.Len() + + /* 判断双向队列是否为空 */ + isEmpty := deque.Len() == 0 ``` === "JavaScript" diff --git a/docs/chapter_stack_and_queue/queue.md b/docs/chapter_stack_and_queue/queue.md index f443f21f0..a663b9745 100644 --- a/docs/chapter_stack_and_queue/queue.md +++ b/docs/chapter_stack_and_queue/queue.md @@ -115,7 +115,29 @@ comments: true === "Go" ```go title="queue.go" + /* 初始化队列 */ + // 在 Go 中,将 list 作为队列来使用 + queue := list.New() + /* 元素入队 */ + queue.PushBack(1) + queue.PushBack(3) + queue.PushBack(2) + queue.PushBack(5) + queue.PushBack(4) + + /* 访问队首元素 */ + peek := queue.Front() + + /* 元素出队 */ + poll := queue.Front() + queue.Remove(poll) + + /* 获取队列的长度 */ + size := queue.Len() + + /* 判断队列是否为空 */ + isEmpty := queue.Len() == 0 ``` === "JavaScript" @@ -309,7 +331,52 @@ comments: true === "Go" ```go title="linkedlist_queue.go" + /* 基于链表实现的队列 */ + type LinkedListQueue struct { + // 使用内置包 list 来实现队列 + data *list.List + } + // NewLinkedListQueue 初始化链表 + func NewLinkedListQueue() *LinkedListQueue { + return &LinkedListQueue{ + data: list.New(), + } + } + + // Offer 入队 + func (s *LinkedListQueue) Offer(value any) { + s.data.PushBack(value) + } + + // Poll 出队 + func (s *LinkedListQueue) Poll() any { + if s.IsEmpty() { + return nil + } + e := s.data.Front() + s.data.Remove(e) + return e.Value + } + + // Peek 访问队首元素 + func (s *LinkedListQueue) Peek() any { + if s.IsEmpty() { + return nil + } + e := s.data.Front() + return e.Value + } + + // Size 获取队列的长度 + func (s *LinkedListQueue) Size() int { + return s.data.Len() + } + + // IsEmpty 判断队列是否为空 + func (s *LinkedListQueue) IsEmpty() bool { + return s.data.Len() == 0 + } ``` === "JavaScript" @@ -540,7 +607,66 @@ comments: true === "Go" ```go title="array_queue.go" + /* 基于环形数组实现的队列 */ + type ArrayQueue struct { + data []int // 用于存储队列元素的数组 + capacity int // 队列容量(即最多容量的元素个数) + front int // 头指针,指向队首 + rear int // 尾指针,指向队尾 + 1 + } + // NewArrayQueue 基于环形数组实现的队列 + func NewArrayQueue(capacity int) *ArrayQueue { + return &ArrayQueue{ + data: make([]int, capacity), + capacity: capacity, + front: 0, + rear: 0, + } + } + + // Size 获取队列的长度 + func (q *ArrayQueue) Size() int { + size := (q.capacity + q.rear - q.front) % q.capacity + return size + } + + // IsEmpty 判断队列是否为空 + func (q *ArrayQueue) IsEmpty() bool { + return q.rear-q.front == 0 + } + + // Offer 入队 + func (q *ArrayQueue) Offer(v int) { + // 当 rear == capacity 表示队列已满 + if q.Size() == q.capacity { + return + } + // 尾结点后添加 + q.data[q.rear] = v + // 尾指针向后移动一位,越过尾部后返回到数组头部 + q.rear = (q.rear + 1) % q.capacity + } + + // Poll 出队 + func (q *ArrayQueue) Poll() any { + if q.IsEmpty() { + return nil + } + v := q.data[q.front] + // 队头指针向后移动一位,若越过尾部则返回到数组头部 + q.front = (q.front + 1) % q.capacity + return v + } + + // Peek 访问队首元素 + func (q *ArrayQueue) Peek() any { + if q.IsEmpty() { + return nil + } + v := q.data[q.front] + return v + } ``` === "JavaScript" diff --git a/docs/chapter_stack_and_queue/stack.md b/docs/chapter_stack_and_queue/stack.md index c2a1ad14d..80870a078 100644 --- a/docs/chapter_stack_and_queue/stack.md +++ b/docs/chapter_stack_and_queue/stack.md @@ -115,7 +115,29 @@ comments: true === "Go" ```go title="stack.go" + /* 初始化栈 */ + // 在 Go 中,推荐将 Slice 当作栈来使用 + var stack []int + /* 元素入栈 */ + stack = append(stack, 1) + stack = append(stack, 3) + stack = append(stack, 2) + stack = append(stack, 5) + stack = append(stack, 4) + + /* 访问栈顶元素 */ + peek := stack[len(stack)-1] + + /* 元素出栈 */ + pop := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + /* 获取栈的长度 */ + size := len(stack) + + /* 判断是否为空 */ + isEmpty := len(stack) == 0 ``` === "JavaScript" @@ -282,7 +304,52 @@ comments: true === "Go" ```go title="linkedlist_stack.go" + /* 基于链表实现的栈 */ + type LinkedListStack struct { + // 使用内置包 list 来实现栈 + data *list.List + } + // NewLinkedListStack 初始化链表 + func NewLinkedListStack() *LinkedListStack { + return &LinkedListStack{ + data: list.New(), + } + } + + // Push 入栈 + func (s *LinkedListStack) Push(value int) { + s.data.PushBack(value) + } + + // Pop 出栈 + func (s *LinkedListStack) Pop() any { + if s.IsEmpty() { + return nil + } + e := s.data.Back() + s.data.Remove(e) + return e.Value + } + + // Peek 访问栈顶元素 + func (s *LinkedListStack) Peek() any { + if s.IsEmpty() { + return nil + } + e := s.data.Back() + return e.Value + } + + // Size 获取栈的长度 + func (s *LinkedListStack) Size() int { + return s.data.Len() + } + + // IsEmpty 判断栈是否为空 + func (s *LinkedListStack) IsEmpty() bool { + return s.data.Len() == 0 + } ``` === "JavaScript" @@ -426,7 +493,53 @@ comments: true === "Go" ```go title="array_stack.go" + /* 基于数组实现的栈 */ + type ArrayStack struct { + data []int // 数据 + } + func NewArrayStack() *ArrayStack { + return &ArrayStack{ + // 设置栈的长度为 0,容量为 16 + data: make([]int, 0, 16), + } + } + + // Size 栈的长度 + func (s *ArrayStack) Size() int { + return len(s.data) + } + + // IsEmpty 栈是否为空 + func (s *ArrayStack) IsEmpty() bool { + return s.Size() == 0 + } + + // Push 入栈 + func (s *ArrayStack) Push(v int) { + // 切片会自动扩容 + s.data = append(s.data, v) + } + + // Pop 出栈 + func (s *ArrayStack) Pop() any { + // 弹出栈前,先判断是否为空 + if s.IsEmpty() { + return nil + } + val := s.Peek() + s.data = s.data[:len(s.data)-1] + return val + } + + // Peek 获取栈顶元素 + func (s *ArrayStack) Peek() any { + if s.IsEmpty() { + return nil + } + val := s.data[len(s.data)-1] + return val + } ``` === "JavaScript" diff --git a/docs/chapter_tree/binary_search_tree.md b/docs/chapter_tree/binary_search_tree.md index a1554e96d..30d392999 100644 --- a/docs/chapter_tree/binary_search_tree.md +++ b/docs/chapter_tree/binary_search_tree.md @@ -88,7 +88,25 @@ comments: true === "Go" ```go title="binary_search_tree.go" - + /* 查找结点 */ + func (bst *BinarySearchTree) Search(num int) *TreeNode { + node := bst.root + // 循环查找,越过叶结点后跳出 + for node != nil { + if node.Val < num { + // 目标结点在 root 的右子树中 + node = node.Right + } else if node.Val > num { + // 目标结点在 root 的左子树中 + node = node.Left + } else { + // 找到目标结点,跳出循环 + break + } + } + // 返回目标结点 + return node + } ``` === "JavaScript" @@ -187,7 +205,36 @@ comments: true === "Go" ```go title="binary_search_tree.go" - + /* 插入结点 */ + func (bst *BinarySearchTree) Insert(num int) *TreeNode { + cur := bst.root + // 若树为空,直接提前返回 + if cur == nil { + return nil + } + // 待插入结点之前的结点位置 + var prev *TreeNode = nil + // 循环查找,越过叶结点后跳出 + for cur != nil { + if cur.Val == num { + return nil + } + prev = cur + if cur.Val < num { + cur = cur.Right + } else { + cur = cur.Left + } + } + // 插入结点 + node := NewTreeNode(num) + if prev.Val < num { + prev.Right = node + } else { + prev.Left = node + } + return cur + } ``` === "JavaScript" @@ -365,7 +412,60 @@ comments: true === "Go" ```go title="binary_search_tree.go" - + /* 删除结点 */ + func (bst *BinarySearchTree) Remove(num int) *TreeNode { + cur := bst.root + // 若树为空,直接提前返回 + if cur == nil { + return nil + } + // 待删除结点之前的结点位置 + var prev *TreeNode = nil + // 循环查找,越过叶结点后跳出 + for cur != nil { + if cur.Val == num { + break + } + prev = cur + if cur.Val < num { + // 待删除结点在右子树中 + cur = cur.Right + } else { + // 待删除结点在左子树中 + cur = cur.Left + } + } + // 若无待删除结点,则直接返回 + if cur == nil { + return nil + } + // 子结点数为 0 或 1 + if cur.Left == nil || cur.Right == nil { + var child *TreeNode = nil + // 取出待删除结点的子结点 + if cur.Left != nil { + child = cur.Left + } else { + child = cur.Right + } + // 将子结点替换为待删除结点 + if prev.Left == cur { + prev.Left = child + } else { + prev.Right = child + } + // 子结点数为 2 + } else { + // 获取中序遍历中待删除结点 cur 的下一个结点 + next := bst.GetInorderNext(cur) + temp := next.Val + // 递归删除结点 next + bst.Remove(next.Val) + // 将 next 的值复制给 cur + cur.Val = temp + } + return cur + } ``` === "JavaScript" diff --git a/docs/chapter_tree/binary_tree.md b/docs/chapter_tree/binary_tree.md index 2fd44c3cc..d7c35d928 100644 --- a/docs/chapter_tree/binary_tree.md +++ b/docs/chapter_tree/binary_tree.md @@ -44,7 +44,20 @@ comments: true === "Go" ```go title="" - + """ 链表结点类 """ + type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode + } + """ 结点初始化方法 """ + func NewTreeNode(v int) *TreeNode { + return &TreeNode{ + Left: nil, + Right: nil, + Val: v, + } + } ``` === "JavaScript" @@ -163,7 +176,18 @@ comments: true === "Go" ```go title="binary_tree.go" - + /* 初始化二叉树 */ + // 初始化结点 + n1 := NewTreeNode(1) + n2 := NewTreeNode(2) + n3 := NewTreeNode(3) + n4 := NewTreeNode(4) + n5 := NewTreeNode(5) + // 构建引用指向(即指针) + n1.Left = n2 + n1.Right = n3 + n2.Left = n4 + n2.Right = n5 ``` === "JavaScript" @@ -228,7 +252,14 @@ comments: true === "Go" ```go title="binary_tree.go" + /* 插入与删除结点 */ + // 在 n1 -> n2 中间插入结点 P + p := NewTreeNode(0) + n1.Left = p + p.Left = n2 + // 删除结点 P + n1.Left = n2 ``` === "JavaScript" @@ -328,7 +359,29 @@ comments: true === "Go" ```go title="binary_tree_bfs.go" - + /* 层序遍历 */ + func levelOrder(root *TreeNode) []int { + // 初始化队列,加入根结点 + queue := list.New() + queue.PushBack(root) + // 初始化一个切片,用于保存遍历序列 + nums := make([]int, 0) + for queue.Len() > 0 { + // poll + node := queue.Remove(queue.Front()).(*TreeNode) + // 保存结点 + nums = append(nums, node.Val) + if node.Left != nil { + // 左子结点入队 + queue.PushBack(node.Left) + } + if node.Right != nil { + // 右子结点入队 + queue.PushBack(node.Right) + } + } + return nums + } ``` === "JavaScript" @@ -446,7 +499,38 @@ comments: true === "Go" ```go title="binary_tree_dfs.go" + /* 前序遍历 */ + func preOrder(node *TreeNode) { + if node == nil { + return + } + // 访问优先级:根结点 -> 左子树 -> 右子树 + nums = append(nums, node.Val) + preOrder(node.Left) + preOrder(node.Right) + } + /* 中序遍历 */ + func inOrder(node *TreeNode) { + if node == nil { + return + } + // 访问优先级:左子树 -> 根结点 -> 右子树 + inOrder(node.Left) + nums = append(nums, node.Val) + inOrder(node.Right) + } + + /* 后序遍历 */ + func postOrder(node *TreeNode) { + if node == nil { + return + } + // 访问优先级:左子树 -> 右子树 -> 根结点 + postOrder(node.Left) + postOrder(node.Right) + nums = append(nums, node.Val) + } ``` === "JavaScript"