二叉树的所有路径

题目

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]
示例 2:

输入:root = [1]
输出:["1"]

提示:

树中节点的数目在范围 [1, 100] 内
-100 <= Node.val <= 100

思路

  • 首先这个看似是一个普通的题目,实则需要考虑两个问题,第一个是如何将实数变成字符串,可以采用to_string()解决。
  • 其次,因为回溯的时候不好回溯,所以最好是记录所有的整数之后,在记录答案的时候变成字符串。
  • 最后, 如果按照一般的回溯写法,你会发现叶子节点判断错误,最后一个节点没有记录的错误,所以要修改代码。

代码

/**
 * 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) {}
 * };
 */
 //最好path中不要直接记录字符串,因为不好回溯,下面这种叶子节点是没办法判断的
// class Solution {
// public:
//     vector<string> result;
//     vector<int> nums;
//     void dfs(TreeNode* cur) {
//         if(cur == NULL) {
//             //将int数组转换成string
//             string path;
//             for(int num : nums) {
//                 path += to_string(num);
//                 path += "->";
//             }
//             path.pop_back();
//             path.pop_back();
//             result.push_back(path);
//             return;
//         }
//         //往左节点走
//         nums.push_back(cur->val);
//         dfs(cur->left);
//         nums.pop_back();
//         //往右节点走
//         nums.push_back(cur->val);
//         dfs(cur->right);
//         nums.pop_back();
//     }
//     vector<string> binaryTreePaths(TreeNode* root) {
//         dfs(root);
//         return result;
//     }
// };
class Solution {
public:
    vector<string> result;
    vector<int> nums;
    void dfs(TreeNode* cur) {
        nums.push_back(cur->val);
        if(cur->left == NULL && cur->right == NULL) {
            //将int数组转换成string
            string path;
            for(int num : nums) {
                path += to_string(num);
                path += "->";
            }
            path.pop_back();
            path.pop_back();
            result.push_back(path);
            return;
        }
        //往左节点走
        if(cur->left) {
            dfs(cur->left);
            nums.pop_back();
        }
        if(cur->right) {
            dfs(cur->right);
            nums.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        dfs(root);
        return result;
    }
};
posted @ 2024-03-09 20:44  铜锣湾陈昊男  阅读(5)  评论(0)    收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示