Description
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”]
解题思路:题目要求找出从根节点到所有叶子节点的路径,使用dfs就可以很好的解决问题。关键是如何保存访问过的节点,开始我是用栈来实现dfs,并且建立了一个数组来保存所有节点的父节点的val值,因为只要只要访问到叶子节点时,就可以从叶子节点一路返回到根节点,这种办法行得通的前提是所有的节点的val值都不相同,否则就会出错。另一种方法是使用递归实现dfs,使用这种方法时,我是通过建立一个vector来保存访问过的节点。程序代码如下:
/**
* 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<vector<int>> result; //用来保存所有路径上的节点的val值
void dfs(TreeNode * root, vector<int> &path) { //path保存的是一条路径上的节点的val值
if (root == NULL) {
return;
}
if(root -> left == NULL && root -> right == NULL) {
path.push_back(root -> val);
result.push_back(path);
return;
}
path.push_back(root -> val);
vector<int> temp1(path);
vector<int> temp2(path);
if (root -> left != NULL)
dfs(root -> left, temp1);
if (root -> right != NULL)
dfs(root -> right, temp2);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
dfs(root, path);
vector<string> str;
int size = result.size(); //路径的数目
for (int i = 0; i < size; i++) {
int subsize = result[i].size();
string record;
for (int j = 0; j < subsize; j++) {
stringstream ss;
string n_to_s;
ss << result[i][j];
ss >> n_to_s; //把int转换为string
record = record + n_to_s;
if (j != subsize -1)
record = record + "->"; //record是以字符串表示的路径
}
str.push_back(record);
}
return str;
}
};