leetcode解题: Binary Tree Paths (257)

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
/ \
2 3
\
5
All root-to-leaf paths are:

[“1->2->5”, “1->3”]

解法1: DFS, O(N)

很标准的DFS的题目,要注意的是因为我们需要加入“->”, 所以写法上可以有两种办法。
一个是helper函数的起始string是“”, 那么每次加一个node的时候要判断是否str还是空,是的话不加,不是则加箭头。
另一个是一开始就赋值root->val, 这样每次碰到新node的时候一定需要加上”->”。写法上第二种办法更干净一些。
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (!root) {
return res;
}
helper(root, to_string(root->val), res);
return res;
}
void helper(TreeNode* root, string s, vector<string>& res) {
if (!root) {
return;
}
if (!root->left && !root->right) {
res.push_back(s);
return;
}
if (root->left) {
helper(root->left, s + "->" + to_string(root->left->val), res);
}
if (root->right) {
helper(root->right, s + "->" + to_string(root->right->val), res);
}
return;
}
};

Java

1