leetcode_c++:树:Binary Tree Paths(257)

来源:互联网 发布:暖男的同义网络词 编辑:程序博客网 时间:2024/05/22 13:36

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

求跟到叶子的所有路径。

分析:

直接 DFS 过去求求行了,也就是前序+记录路径。


class Solution {public:    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> ans;        vector<int> path;        dfs(root, path, ans);        return ans;    }private:    void dfs(TreeNode* root, vector<int> &path, vector<string> &ans) {        if (!root) return;        path.push_back(root->val);        if (!root->left && !root->right)            ans.push_back(getString(path));        dfs(root->left, path, ans);        dfs(root->right, path, ans);        path.pop_back();    }    string getString(vector<int> path) {        if (path.empty()) return "";        string ret;        for (int i = 0; i < path.size() - 1; ++i)            ret += to_string(path[i]) + "->";        ret += to_string(path[path.size() - 1]);        return ret;    }};

0 0
原创粉丝点击