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"]
题目大意:
输出二叉树的所有路径
思路:
先序遍历,记录路径。为了回溯,临时存储路径的数据结构得具有弹出最后一个元素的功能,我的代码里面用的是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<string> v;
void dfs(TreeNode* root, vector<string> s) {
if (root == nullptr) return;
if ((root->left == nullptr) && (root->right == nullptr)) {
if(s.size() == 0) s.push_back(to_string(root->val));
else s.push_back("->" + to_string(root->val));
string t = "";
for (int i = 0; i < s.size(); ++i) {
t += s[i];
}
v.push_back(t);
return ;
}
if(s.size() == 0) s.push_back(to_string(root->val));
else s.push_back("->" + to_string(root->val));
dfs(root->left, s);
dfs(root->right, s);
s.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> s;
dfs(root, s);
return v;
}
};