leetcode 257. Binary Tree Paths

 返回所有根到叶子的路径。用个“全局”的ret代替合的过程。

    vector<string> binaryTreePaths(TreeNode* root) {
        if (root == NULL)
            return vector<string>();

        vector<string> ret;
        dfs(root, string(""), ret);
        return ret;
    }
    
    void dfs(TreeNode* root, string now, vector<string>& ret) {
        if (root->left == NULL && root->right == NULL) {
            ret.push_back(now + to_string(root->val));
            return;
        }
        
        now = now + to_string(root->val) + "->";
        if (root->left)
            dfs(root->left, now, ret);
        if (root->right)
            dfs(root->right, now, ret);
    }

 

posted on 2018-02-07 13:29  willaty  阅读(74)  评论(0编辑  收藏  举报

导航