leetcode 257. 二叉树的所有路径
问题描述
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
   1
 /   \
2     3
 \
  5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
代码
/**
 * 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) {
        vector<string> ans;
        string path;
        findpath(root,ans,path);
        return ans;
    }
    void findpath(TreeNode* root,vector<string>& ans,string path)
    {
        if(!root)return;
        path += to_string(root->val);
        if(!root->left && !root->right)
        {
            ans.push_back(path);
            return;
        }
        path += "->";
        findpath(root->left,ans,path);
        findpath(root->right,ans,path);
    }
};
结果:
执行用时 :8 ms, 在所有 C++ 提交中击败了55.16%的用户
内存消耗 :13.9 MB, 在所有 C++ 提交中击败了5.09%的用户
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号