Golang每日一练(leetDay0049) 二叉树专题
warning:
这篇文章距离上次修改已过196天,其中的内容可能已经有所变动。
题目:二叉树的所有路径
给定一个二叉树的根节点 root ,返回所有从根节点到叶子节点的路径。
示例 1:
输入:root = [1,2,3,null,null,null,4]
输出:["1->2->4","1->3"]
示例 2:
输入:root = [1]
输出:["1"]
提示:
树中节点的数目在范围 [1, 100] 内
-100 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
解法:深度优先搜索(DFS)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
var paths []string
var dfs func(node *TreeNode, path string)
dfs = func(node *TreeNode, path string) {
if node == nil {
return
}
if node.Left == nil && node.Right == nil {
paths = append(paths, path+strconv.Itoa(node.Val))
} else {
dfs(node.Left, path+strconv.Itoa(node.Val)+"->")
dfs(node.Right, path+strconv.Itoa(node.Val)+"->")
}
}
dfs(root, "")
return paths
}
这段代码首先定义了一个binaryTreePaths
函数,该函数接收一个二叉树的根节点root
作为参数,并返回从根节点到叶子节点的所有路径。然后定义了一个局部函数dfs
,它接收当前节点node
和当前路径path
作为参数。dfs
函数通过递归遍历二叉树的每个节点,当遇到叶子节点时,将当前的路径加入到结果切片paths
中。如果不是叶子节点,则递归遍历其左右子节点,并在递归调用时将当前节点的值添加到路径中。
评论已关闭