[LeetCode]257. Binary Tree Paths
题目描述
思路
深搜,到叶子节点将当前字符串结果保存到数组中
代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void dfs(TreeNode* root, vector<string>& res, string str) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
res.push_back(str);
return;
}
if (root->left)
dfs(root->left, res, str + "->" + to_string(root->left->val));
if (root->right)
dfs(root->right, res, str + "->" + to_string(root->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root == NULL)
return res;
string str = to_string(root->val);
dfs(root, res, str);
return res;
}
};
int main() {
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(5);
TreeNode* n5 = new TreeNode(6);
n1->left = n2, n1->right = n3;
n2->left = n5;
n2->right = n4;
Solution s;
vector<string> res = s.binaryTreePaths(n1);
for (auto str : res) {
cout << str << " ";
}
cout << endl;
system("pause");
return 0;
}