思路
除去根节点,每一层添加->val,然后使用前序遍历的顺序
代码
class Solution {
public:
vector<string> res;
void getTreePaths(string s, TreeNode* root){
s += "->";
s += to_string(root->val);
if(root->left == nullptr && root->right == nullptr){
res.push_back(s);
return;
}
if(root->left) getTreePaths(s, root->left);
if(root->right) getTreePaths(s, root->right);
}
vector<string> binaryTreePaths(TreeNode* root) {
if(root->left == nullptr && root->right == nullptr){
res.push_back(to_string(root->val));
return res;
}
string s;
if(root->left) getTreePaths(to_string(root->val), root->left);
if(root->right) getTreePaths(to_string(root->val), root->right);
return res;
}
};