代码随想录算法训练营 | 博客打卡
题目链接:leetcode 257. 二叉树的所有路径
注:仅为个人笔记,难以细致且通俗。
func binaryTreePaths(root *TreeNode) []string {
res := make([]string, 0)
getPathStr := func(path string, val int) string {
if path == "" {
return strconv.Itoa(val)
} else {
return path + "->" + strconv.Itoa(val)
}
}
var travel func(node *TreeNode, path string)
travel = func(node *TreeNode, path string){
if node == nil {
res = append(res, path)
return
}
path = getPathStr(path, node.Val)
travel(node.Left, path)
travel(node.Right, path)
return
}
travel(root, "")
return res
}
一开始写错了,没理解题意。
一直向下延伸,一路添加元素到路径上,直到抵达叶子节点,然后把完整的路径添加到数组中。
func binaryTreePaths(root *TreeNode) []string {
res := make([]string, 0)
getPathStr := func(path string, val int) string {
if path == "" {
return strconv.Itoa(val)
} else {
return path + "->" + strconv.Itoa(val)
}
}
var travel func(node *TreeNode, path string)
travel = func(node *TreeNode, path string){
path = getPathStr(path, node.Val)
if node.Left == nil && node.Right == nil {
res = append(res, path)
return
}
if node.Left != nil {
travel(node.Left, path)
}
if node.Right != nil {
travel(node.Right, path)
}
return
}
travel(root, "")
return res
}