前言
在LeetCode上刷题时 有的时候自己无法理解和追踪某个变量的变化 因此需要debug代码 但LeetCode的debug功能很鸡肋 不如自己在本地编译器中进行断点调试 但LeetCode的解题只需要写出功能的函数即可 所以我们需要自己补写出其他函数来保证debug的成功
链表模版
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
| package main
import ( "fmt" )
type ListNode struct { Val int Next *ListNode }
func createList(nums []int) *ListNode { prev := new(ListNode) prev.Val = nums[0] prevHead := new(ListNode) prevHead = prev for i:=1;i<len(nums);i++ { temp := new(ListNode) temp.Val = nums[i] prev.Next = temp prev = temp } return prevHead }
func ShowList(L *ListNode) { temp := L for temp != nil { fmt.Print(temp.Val," ") temp = temp.Next } fmt.Println() }
|
树模版
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
|
type TreeNode struct { Val int Left *TreeNode Right *TreeNode }
func createTree(nums []int, len int, index int) *TreeNode { root := new(TreeNode) if index < len && nums[index] != -1 { root.Val = nums[index] if 2*index+1 < len { root.Left = createTree(nums, len, 2*index+1) } if 2*index+2 < len { root.Right = createTree(nums, len, 2*index+2) } } return root }
func levelOrder(root *TreeNode) [][]int { res := [][]int{} if root == nil { return res } queue := []*TreeNode{root} for i := 0; len(queue) > 0; i++ { res = append(res, []int{}) temp := []*TreeNode{} for j := 0; j < len(queue); j++ { node := queue[j] res[i] = append(res[i], node.Val) if node.Left != nil { temp = append(temp, node.Left) } if node.Right != nil { temp = append(temp, node.Right) } } queue = temp } return res }
func PrintMartrix(res [][]int) { for i := 0; i < len(res); i++ { fmt.Print("[") for j := 0; j < len(res[i]); j++ { fmt.Print(" ", res[i][j], " ") } fmt.Println("]") } }
|