LeetCode257. 二叉树的所有路径Golang版
1. 问题描述
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
2. 思路
深度优先遍历,遍历过程中检测是否为叶子节点,并进行收集
3. 代码
// 第一次刷题版本
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var paths []string
func binaryTreePaths(root *TreeNode) []string {
paths = []string{}
constructPaths(root,"")
return paths
}
func constructPaths(root *TreeNode,path string) {
if root != nil {
pathSB := path
pathSB += strconv.Itoa(root.Val)
if root.Left == nil && root.Right == nil {
paths = append(paths,pathSB)
} else {
pathSB += "->"
constructPaths(root.Left,pathSB)
constructPaths(root.Right,pathSB)
}
}
}
// 第二次刷题更改
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
paths := []string{}
constructPaths(root,"", &paths)
return paths
}
func constructPaths(root *TreeNode,path string, paths *[]string) {
if root == nil {
return
}
path += strconv.Itoa(root.Val)
if root.Left == nil && root.Right == nil {
*paths = append(*paths,path)
} else {
path += "->"
constructPaths(root.Left, path, paths)
constructPaths(root.Right, path, paths)
}
}
3.2 另一种写法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
// var res []string = []string{}
res := []string{}
if root == nil {
return res
}
// var path []int
path := []int{}
constructPaths(root,path, &res)
return res
}
func constructPaths(root *TreeNode,path []int, res *[]string) {
path = append(path, root.Val)
if root.Left == nil && root.Right == nil {
var strPath string
for i := 0; i < len(path) - 1; i++ {
strPath += strconv.Itoa(path[i])
strPath += "->"
}
strPath += strconv.Itoa(path[len(path) - 1])
*res = append(*res, strPath)
return
}
if root.Left != nil {
constructPaths(root.Left, path, res)
}
if root.Right != nil {
constructPaths(root.Right, path, res)
}
}
3.3. 回溯模板
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
var res []string
if root == nil {
return res
}
var path []int
path = append(path, root.Val)
constructPaths(root, path, &res)
return res
}
func constructPaths(root *TreeNode,path []int, res *[]string) {
if root.Left == nil && root.Right == nil {
// temp := make([]int, len(path))
// copy(temp, path)
// path = temp
var strPath string
for i := 0; i < len(path) - 1; i++ {
strPath += strconv.Itoa(path[i])
strPath += "->"
}
strPath += strconv.Itoa(path[len(path) - 1])
*res = append(*res, strPath)
return
}
if root.Left != nil {
path = append(path, root.Left.Val)
constructPaths(root.Left, path, res)
path = path[:len(path) - 1]
}
if root.Right != nil {
path = append(path, root.Right.Val)
constructPaths(root.Right, path, res)
path = path[:len(path) - 1]
}
return
}