Skip to content

Latest commit

 

History

History
83 lines (65 loc) · 1.85 KB

257-binary-tree-paths.md

File metadata and controls

83 lines (65 loc) · 1.85 KB

257. Binary Tree Paths - 二叉树的所有路径

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

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

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

题目标签:Tree / Depth-first Search

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 8 ms N/A
/**
 * 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> res;
    vector<int> path;
    string join(vector<int>& p, string delimiter){
        stringstream ss;
        for(int i=0; i<p.size(); i++){
            if(i) { ss << delimiter; }
            ss << to_string(p[i]);
        }
        return ss.str();
    }
    void dfs(TreeNode* node){
        if(!node){
            return;
        }
        path.push_back(node->val);
        if(node->left){
            dfs(node->left);
            path.pop_back();
        }
        if(node->right){
            dfs(node->right);
            path.pop_back();
        }
        if(!node->left && !node->right){
            res.push_back(join(path, "->"));
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        dfs(root);
        return res;
    }
};