funcgenerateMatrix(n int) [][]int { // 生成一个空矩阵 matrix := make([][]int, n) for i := 0; i < n; i++ { matrix[i] = make([]int, n) } // 定义上下左右边界 up, down, left, right := 0, n-1, 0, n-1 num := 1// 待填入的数字 // 螺旋遍历矩阵,填入数字 for num <= n*n { // 填写上边界 for i := left; i <= right; i++ { matrix[up][i] = num num++ } up++ // 填写右边界 for i := up; i <= down; i++ { matrix[i][right] = num num++ } right-- // 填写下边界 for i := right; i >= left; i-- { matrix[down][i] = num num++ } down-- // 填写左边界 for i := down; i >= up; i-- { matrix[i][left] = num num++ } left++ }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcpostorderTraversal(root *TreeNode) []int { res := []int{} var postorder func(root *TreeNode) postorder = func(root *TreeNode) { if root != nil { postorder(root.Left) postorder(root.Right) res = append(res, root.Val) } } postorder(root)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcpostorderTraversal(root *TreeNode) []int { res := make([]int, 0) stack := make([]*TreeNode, 0) cur := root var pre *TreeNode
forlen(stack) > 0 || cur != nil { for cur != nil { stack = append(stack, cur) cur = cur.Left } iflen(stack) > 0 { cur = stack[len(stack)-1] if cur.Right == nil || pre == cur.Right { // 若栈顶节点右子树为空,或者刚刚遍历过右子树 // 遍历栈顶节点并弹出 res = append(res, cur.Val) pre = cur stack = stack[:len(stack)-1] cur = nil } else { // 否则进入右子树 cur = cur.Right } } }
func(path Path)TranslateBy(offset Point, add bool) { var op func(p, q Point)Point if add { op = Point.Add } else { op = Point.Sub } for i := range path { // Call either path[i].Add(offset) or path[i].Sub(offset). path[i] = op(path[i], offset) } }