二叉树的所有路径考查的就是我们的递归和回溯的技巧。

递归用来进行二叉树节点的遍历,回溯用于单条路径的存储(递归回溯则路径也跟着回溯)。

该题的经典步骤:

  • 1 处理叶子节点
  • 2 处理左节点,路径回溯
  • 3 处理右节点,路径回溯

递归的两种方式:

  • 1 递归出口判断叶子节点,root->left和root->right需要判断是否为空
  • 2 递归出口判断root节点,root->left和root->right不需要判断是否为空
/**
 * 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 result;
    void getPath(TreeNode* root, vector& path){
        path.push_back(root->val);
        // 1 叶子节点
        if (root->left == nullptr && root->right == nullptr){
            string spath;
            for(int i=0; i<path.size()-1; i++){ spath += to_string(path[i]); spath += "->";
            }
            spath += to_string(path[path.size()-1]);
            result.push_back(spath);
            return;
        }
        // 2 left and right
        if (root->left){
            getPath(root->left, path);
            path.pop_back();
        }
        if (root->right){
            getPath(root->right, path);
            path.pop_back();
        }
    }

    vector binaryTreePaths(TreeNode* root) {
        vector path;
        getPath(root, path);
        return result;
    }
};