注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
LC257 https://leetcode.com/problems/binary-tree-paths/
一道简单题,我觉得我的解题思路没问题(源代码在最后)。但是不知道为啥在test case 188(如下图)时总是遇到bug
![]()
正确答案显然应该是 ["6->1->3->2","6->1->3->5->4"]
但是我的程序输出的是 ["6->1->3->5","6->1->3->5->4"]
最神奇的是,如果uncoment第21行打印*cur的值,正是答案所需的 [6 1 3 2] 和 [6 1 3 5 4]。但我不明白为啥append到res里面就变了呢😵 求大佬帮忙看看。回复必加米!先谢过了!
- /**
- * Definition for a binary tree node.
- * type TreeNode struct {
- * Val int
- * Left *TreeNode
- * Right *TreeNode
- * }
- */
- func binaryTreePaths(root *TreeNode) []string {
- s := make([]string, 0)
- res := make([][]string, 0)
-
- var dfs func(*TreeNode, *[]string)
- dfs = func(node *TreeNode, cur *[]string) {
- if node==nil {
- return
- }
- *cur = append(*cur, strconv.Itoa(node.Val))
- if node.Left==nil && node.Right==nil {
- //fmt.Println(*cur)
- res = append(res, *cur)
- }
- dfs(node.Left, cur)
- dfs(node.Right, cur)
- *cur = (*cur)[:(len(*cur)-1)]
- }
-
-
- dfs(root, &s)
- out := make([]string, len(res))
-
- //fmt.Println(res)
- for i:=0; i<len(res); i++ {
- out[i] = strings.Join(res[i], "->")
- }
-
- return out
- }
复制代码
|