Golang Leetcode 257. Binary Tree Paths.go

时间:2022-06-19
本文章向大家介绍Golang Leetcode 257. Binary Tree Paths.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89055044

思路

二叉树常规遍历

code

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func binaryTreePaths(root *TreeNode) []string {
	s := []string{}
	if root == nil {
		return s
	}
	helper(root, strconv.Itoa(root.Val), &s)
	return s
}

func helper(node *TreeNode, path string, s *[]string) {
	if node.Left == nil && node.Right == nil {
		*s = append(*s, path)
	}
	if node.Left != nil {
		helper(node.Left, path+"->"+strconv.Itoa(node.Left.Val), s)
	}
	if node.Right != nil {
		helper(node.Right, path+"->"+strconv.Itoa(node.Right.Val), s)
	}

}