给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
解题思路:
递归加回溯–使用前序遍历遍历到叶节点回溯。
递归三部曲
1.确定递归函数的返回值和参数每次调用的参数,每次传参需要将当前调用的节点,数组和最终返回结果传入,函数没有返回值。
2.什么时候截止呢,是当 cur不为空,其左右孩⼦都为空的时候,就找到叶⼦节点。
3.单层逻辑,二叉树左子树右子树递归。直到访问到叶子节点返回,说明一条路径已经查找结束,退出当前节点。
/**
* 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:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>res;
vector<int>path;
if(root==NULL) return res;
traversal(root,path,res);
return res;
}
//递归+回溯
void traversal(TreeNode* cur,vector<int>& path,vector<string>& result)
{
path.push_back(cur->val);
if(cur->left==NULL&&cur->right==NULL)
{
string str="";
int size=path.size();
for(int i=0;i<size-1;i++)
{
str+=to_string(path[i]);
str+="->";
}
str+=to_string(path[path.size()-1]);
result.push_back(str);
return;
}
if(cur->left) {
traversal(cur->left,path,result);
path.pop_back();
}
if(cur->right){
traversal(cur->right,path,result);
path.pop_back();
}
}
};