Files
LeetCode-Go/website/content/ChapterFour/0257.Binary-Tree-Paths.md
2020-08-09 00:39:24 +08:00

71 lines
1.2 KiB
Markdown
Executable File
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [257. Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)
## 题目
Given a binary tree, return all root-to-leaf paths.
**Note**: A leaf is a node with no children.
**Example**:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
## 题目大意
给定一个二叉树,返回所有从根节点到叶子节点的路径。说明: 叶子节点是指没有子节点的节点。
## 解题思路
- Google 的面试题,考察递归
## 代码
```go
package leetcode
import (
"strconv"
)
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func binaryTreePaths(root *TreeNode) []string {
if root == nil {
return []string{}
}
res := []string{}
if root.Left == nil && root.Right == nil {
return []string{strconv.Itoa(root.Val)}
}
tmpLeft := binaryTreePaths(root.Left)
for i := 0; i < len(tmpLeft); i++ {
res = append(res, strconv.Itoa(root.Val)+"->"+tmpLeft[i])
}
tmpRight := binaryTreePaths(root.Right)
for i := 0; i < len(tmpRight); i++ {
res = append(res, strconv.Itoa(root.Val)+"->"+tmpRight[i])
}
return res
}
```