LeetCode 257 Bianry Tree Paths(二叉树路径保存)

来源:互联网 发布:macbook不能下载软件 编辑:程序博客网 时间:2024/06/05 05:12

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

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

题目大意:给出一个二叉树,返回其所有路径。

解题思路:DFS

代码如下:

/** * 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;        if(root != nullptr) dfs(root, "", ans);        return ans;    }private:    void dfs(TreeNode* root, string path, vector<string>& ans) {        if(root->left == nullptr && root->right == nullptr) {            ans.push_back(path + to_string(root->val));            return ;        }                    if(root->left)             dfs(root->left, path + to_string(root->val) + "->", ans);        if(root->right)            dfs(root->right, path + to_string(root->val) + "->", ans);    }    };

阅读全文
0 0