题目链接:https://leetcode.com/problems/binary-tree-paths/
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"]
思路:先序遍历二叉树将路径上的每一个值加到一条路径的字符串中
/**
* 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:
void DFS(TreeNode* root, string cur)
{
if(!root) return;
cur += to_string(root->val);
if(!root->left && !root->right) result.push_back(cur);
DFS(root->left, cur + "->");
DFS(root->right, cur + "->");
}
vector<string> binaryTreePaths(TreeNode* root) {
DFS(root, string(""));
return result;
}
private:
vector<string> result;
};