257. 二叉树的所有路径
一、递归
前序遍历,递归终止条件为左右孩子都为空,说明当前结点为叶子结点,然后将路径添加至结果中,单层递归逻辑同前序遍历,在递归后回溯,每个递归都要有对应的回溯
class Solution {
public:
void dfs(TreeNode* node,vector<int> &path,vector<string> &result)
{
//中
path.push_back(node->val);
if(node->left==NULL && node->right==NULL)
{
string s;
for(int i =0;i<path.size()-1;i++)
{
s += to_string(path[i]);
s += "->";
}
s += to_string(path[path.size()-1]);
result.push_back(s);
}
//左
if(node->left)
{
dfs(node->left,path,result);
path.pop_back();
}
//右
if(node->right)
{
dfs(node->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(root==NULL)return {};
vector<string> result;
vector<int> path;
dfs(root,path,result);
return result;
}
};
简化
通过函数的参数进行回溯操作
class Solution {
private:
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); // 右
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};