leetcode 257. 二叉树的所有路径(Binary Tree Paths)

题目描述:

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

    输入:

       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:
    string toString(long long val){
        string res = "";
        if(val == 0){
            return "0";
        }else{
            bool neg = false;
            if(val < 0){
                neg = true;
                val = -val;
            }
            while(val){
                res = char('0' + val%10) + res;
                val /= 10;
            }
            if(neg){
                res = '-' + res;
            }
            return res;
        }
    }
    
    string toString(vector<int>& lst){
        string res = "";
        if(lst.empty()){
            return res;
        }else{
            for(int val : lst){
                res += "->" + toString(val);
            }
            return res.substr(2);
        }
        
    }
    
    void binaryTreePaths(TreeNode* root, vector<string>& res, vector<int>& cur){
        if(root){
            cur.push_back(root->val);
            if(!root->left && !root->right){
                res.push_back(toString(cur));
            }else{
                if(root->left){
                    binaryTreePaths(root->left, res, cur);
                }
                if(root->right){
                    binaryTreePaths(root->right, res, cur);
                }
            }
            cur.pop_back();
        }
    }
    
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        vector<int> cur;
        binaryTreePaths(root, res, cur);
        return res;
    }
};
posted @ 2019-03-21 14:56  zhanzq1  阅读(115)  评论(0)    收藏  举报