题目:
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
注:叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5]
输出:[“1->2->5”,“1->3”]
示例 2:
输入:root = [1]
输出:[“1”]
代码:
func binaryTreePaths(root *TreeNode) []string {
// 如果根节点为空,则返回空节点
if root == nil {
return []string{}
}
// 如果根节点没有子节点,则直接将该点的值返回出去
if root.Left == nil && root.Right == nil {
return []string{strconv.Itoa(root.Val)}
}
// 创建结果字符串列表
res := []string{}
// 搜寻左子节点
tmpLeft := binaryTreePaths(root.Left)
for i := 0; i < len(tmpLeft); i++ {
res = append(res, strconv.Itoa(root.Val)+"->"+tmpLeft[i])
}
// 搜寻右子节点
tmpRight := binaryTreePaths(root.Right)
for i := 0; i < len(tmpRight); i++ {
res = append(res, strconv.Itoa(root.Val)+"->"+tmpRight[i])
}
return res
}
这篇博客介绍了如何用递归方式解决二叉树的路径遍历问题,给出了具体的Go语言代码实现。通过遍历根节点的左右子树,收集所有从根节点到叶子节点的路径。
331

被折叠的 条评论
为什么被折叠?



