257. 二叉树的所有路径

一、递归

前序遍历,递归终止条件为左右孩子都为空,说明当前结点为叶子结点,然后将路径添加至结果中,单层递归逻辑同前序遍历,在递归后回溯,每个递归都要有对应的回溯

  1. class Solution {
  2. public:
  3. void dfs(TreeNode* node,vector<int> &path,vector<string> &result)
  4. {
  5. //中
  6. path.push_back(node->val);
  7. if(node->left==NULL && node->right==NULL)
  8. {
  9. string s;
  10. for(int i =0;i<path.size()-1;i++)
  11. {
  12. s += to_string(path[i]);
  13. s += "->";
  14. }
  15. s += to_string(path[path.size()-1]);
  16. result.push_back(s);
  17. }
  18. //左
  19. if(node->left)
  20. {
  21. dfs(node->left,path,result);
  22. path.pop_back();
  23. }
  24. //右
  25. if(node->right)
  26. {
  27. dfs(node->right,path,result);
  28. path.pop_back();
  29. }
  30. }
  31. vector<string> binaryTreePaths(TreeNode* root) {
  32. if(root==NULL)return {};
  33. vector<string> result;
  34. vector<int> path;
  35. dfs(root,path,result);
  36. return result;
  37. }
  38. };

简化

通过函数的参数进行回溯操作

  1. class Solution {
  2. private:
  3. void traversal(TreeNode* cur, string path, vector<string>& result) {
  4. path += to_string(cur->val); // 中
  5. if (cur->left == NULL && cur->right == NULL) {
  6. result.push_back(path);
  7. return;
  8. }
  9. if (cur->left) traversal(cur->left, path + "->", result); // 左
  10. if (cur->right) traversal(cur->right, path + "->", result); // 右
  11. }
  12. public:
  13. vector<string> binaryTreePaths(TreeNode* root) {
  14. vector<string> result;
  15. string path;
  16. if (root == NULL) return result;
  17. traversal(root, path, result);
  18. return result;
  19. }
  20. };