【LeetCode】二叉树的所有路径

题目描述:

https://leetcode-cn.com/problems/binary-tree-paths/

代码:递归

class Solution {
private:
    vector ans;
public:
    vector binaryTreePaths(TreeNode* root) {
        if(!root)
            return ans;
        DFS(root, to_string(root->val));
        return ans;
    }
    
    void DFS(TreeNode * root, string str)
    {
        if(!root->right && !root->left)
        {
            ans.push_back(str);
            return;
        }
        if(root->left != NULL)
            DFS(root->left, str+"->"+to_string(root->left->val));
        if(root->right != NULL)
            DFS(root->right, str+"->"+to_string(root->right->val));
    }
};

你可能感兴趣的:(【LeetCode】二叉树的所有路径)