- 剑指 Offer 31. 栈的压入、弹出序列
func validateStackSequences(pushed []int, popped []int) bool {
stack := make([]int, 0)
index := 0
for _, val := range pushed {
stack = append(stack, val)
for (len(stack) > 0 && popped[index] == stack[len(stack) - 1]) {
index++
stack = stack[:len(stack) - 1]
}
}
return len(stack) == 0
}
- 剑指 Offer 33. 二叉搜索树的后序遍历序列
- 每次都是一个新的子问题,所以用递归来解决
- 边界条件要控制好
func verifyPostorder(postorder []int) bool {
return verify(postorder, 0, len(postorder) - 1)
}
func verify(post []int, left, right int) bool {
if left >= right {
return true
}
rootVal := post[right]
split := left
for post[split] < rootVal {
split++
}
for split < right {
if post[split] < rootVal {
return false
}
split++
}
return verify(post, left, split - 1) && verify(post, split, right-1)
}
- 剑指 Offer 34. 二叉树中和为某一值的路径
func pathSum(root *TreeNode, sum int) [][]int {
res := make([][]int, 0)
if root == nil {
return res
}
backtrack(root, sum, &res, make([]int, 0))
return res
}
func backtrack(root *TreeNode, sum int, res *[][]int, path []int) {
if root == nil {
return
}
path = append(path, root.Val)
if root.Left == nil && root.Right == nil && sum == root.Val {
tmp := make([]int,len(path))
copy(tmp,path)
*res = append(*res, tmp)
return
}
backtrack(root.Left, sum - root.Val, res, path)
backtrack(root.Right, sum - root.Val, res, path)
path = path[:len(path) - 1]
}