Leetcode 257. 二叉树的所有路径 解题思路及C++实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gjh13/article/details/90742767

解题思路:

使用深度优先搜索(DFS),深度优先搜索的终止条件是:当前节点root为叶子节点,即:!root->left && !root->right 为真,则找到了一条路径。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root){
        if(!root) return {};
        
        vector<string> res;
        dfs(res, root, to_string(root->val));
        return res;
    }
    void dfs(vector<string>& res, TreeNode* root, string tmp){
        if(!root->left && !root->right){
            res.push_back(tmp);
            return;
        }
        if(root->left)
            dfs(res, root->left, tmp + "->" + to_string(root->left->val));
        if(root->right)
            dfs(res, root->right, tmp + "->" + to_string(root->right->val));
    }
};

猜你喜欢

转载自blog.csdn.net/gjh13/article/details/90742767