Created
March 28, 2020 21:57
-
-
Save alldroll/b85b248b9f7570c9049c28c8cabe7986 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/binary-tree-paths | |
| /** | |
| * Definition for a binary tree node. | |
| * type TreeNode struct { | |
| * Val int | |
| * Left *TreeNode | |
| * Right *TreeNode | |
| * } | |
| */ | |
| func binaryTreePaths(root *TreeNode) []string { | |
| result := []string{} | |
| findPaths(root, []int{}, &result) | |
| return result | |
| } | |
| func findPaths(root *TreeNode, path []int, result *[]string) { | |
| if root == nil { | |
| return | |
| } | |
| if root.Left != nil { | |
| findPaths(root.Left, append(path, root.Val), result) | |
| } | |
| if root.Left == nil && root.Right == nil { | |
| *result = append(*result, stringifyPath(append(path, root.Val))) | |
| return | |
| } | |
| if root.Right != nil { | |
| findPaths(root.Right, append(path, root.Val), result) | |
| } | |
| } | |
| func stringifyPath(path []int) string { | |
| serialized := "" | |
| for _, x := range path { | |
| if len(serialized) == 0 { | |
| serialized = fmt.Sprintf("%d", x) | |
| } else { | |
| serialized = fmt.Sprintf("%s->%d", serialized, x) | |
| } | |
| } | |
| return serialized | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment