美文网首页
【LeetCode】二叉树的所有路径

【LeetCode】二叉树的所有路径

作者: MyyyZzz | 来源:发表于2019-04-09 22:36 被阅读0次

题目描述:

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

代码:递归

class Solution {
private:
    vector<string> ans;
public:
    vector<string> 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】二叉树的所有路径

      本文链接:https://www.haomeiwen.com/subject/mevwiqtx.html