Fork me on GitHub

leetcode之257. 二叉树的所有路径

题目描述:

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
> 输入:
>
> 1
> / \
> 2 3
> \
> 5
>
> 输出: ["1->2->5", "1->3"]
>
> 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
>

解题思路一:

时间复杂度:$O(n)$, 空间复杂度:$O(1)$.

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
/**
* 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> vec;
string s = "";

if(!root) return vec;

TreePaths(root, s, vec);

return vec;

}

void TreePaths(TreeNode *root, string s, vector<string> &vec)
{


if(root->left || root->right) s = s + to_string(root->val) + "->";

if(!root->left && !root->right)
{
s = s + to_string(root->val);
vec.push_back(s);
s = "";
}

if(root->left)
TreePaths(root->left, s, vec);
if(root->right)
TreePaths(root->right, s, vec);
}
};

解题思路二:

时间复杂度:$O(n)$, 空间复杂度:$O(1)$.

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
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;

if(!root)
return res;

DFS(root, res, to_string(root->val));
return res;
}

// 深度优先搜索
void DFS(TreeNode* root,vector<string> &res,string subPath){
// 如果当前该节点为叶子结点,则此条路径已经遍历完,将路径添加到结果中,并返回
if(root->left==NULL&&root->right==NULL){
res.push_back(subPath);
return;
}

// 左孩子非空
if(root->left){
DFS(root->left, res, subPath + "->" + to_string(root->left->val));
}

// 右孩子非空
if(root->right){
DFS(root->right, res, subPath + "->" + to_string(root->right->val));
}
}};