思路:路径从上到下,可以理解为深度,那么我们用前序遍历的方式,中左右。先把中进行遍历,加入到path,如果左右孩子都为空那么相当于到了叶子节点了,那就把path加到resul里,进行回溯。再处理左再处理右。
题解c++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traversal(TreeNode* cur, string path, vector<string>& result)
{
path+=to_string(cur->val);//中
if(cur->left==NULL&&cur->right==NULL)
{
result.push_back(path);
return;
}//回溯过程
if(cur->left) traversal(cur->left, path +"->", result);//左
if(cur->right) traversal(cur->right, path +"->", result);//右
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
vector<string> result;
if(root==NULL) return result;
traversal(root,path,result);
return result;
}
};