解题思路

path用来保存路径

result保存要返回的字符串

使用前序遍历二叉树,将路过的路径保存到path

代码

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result = []
s = ""
def dfs(root, s):
if root is None:
return
s += str(root.val) + "->"
if (not root.left) and (not root.right):
result.append(s[:len(s) - 2])
return
dfs(root.left, s)
dfs(root.right, s)
dfs(root, s)
return result

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
void traversal(TreeNode* cur, vector<int> &path, vector<string> &result){
path.push_back(cur->val);
// 叶子节点
if (cur->left == NULL && cur->right == NULL){
string sPath;
for (int i = 0; i < path.size() - 1; ++i){
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
// 下一个节点不为空时
if (cur->left) {
traversal(cur->left, path, result);
path.pop_back();
}
if (cur->right) {
traversal(cur->right, path, result);
path.pop_back();
}
}
};

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var paths []string

func binaryTreePaths(root *TreeNode) []string {
paths = []string{}
constructPaths(root, "")
return paths
}

func constructPaths(root *TreeNode, path string) {
if root != nil {
pathSB := path
pathSB += strconv.Itoa(root.Val)
if root.Left == nil && root.Right == nil {
paths = append(paths, pathSB)
} else {
pathSB += "->"
constructPaths(root.Left, pathSB)
constructPaths(root.Right, pathSB)
}
}
}