Golang Leetcode 257. Binary Tree Paths.go

2019-04-12 13:54:38 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412943

思路

二叉树常规遍历

code

代码语言:javascript复制
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)
	}

}

0 人点赞