题目描述
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
解题思想
利用了回溯
代码
class Solution {
public:
void traversal(TreeNode* node, vector<int> &path, vector<string>& res) {
path.push_back(node->val);
if (node->left == nullptr && node->right == nullptr) {
string sPath;
for (int i = 0; i < path.size() - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
res.push_back(sPath);
return;
}
if (node->left) {
traversal(node->left, path, res);
path.pop_back(); //回溯
}
if (node->right) {
traversal(node->right, path, res);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == nullptr) return result;
traversal(root, path, result);
return result;
}
};
简单代码
class Solution {
public:
void traversal(TreeNode* node, string path,vector<string> &res) {
path += to_string(node->val);
if (node->left == nullptr && node->right == nullptr) {
res.push_back(path);
return;
}
if (node->left) traversal(node->left, path + "->", res);
if (node->right) traversal(node->right, path + "->", res);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == nullptr) return result;
traversal(root, path, result);
return result;
}
};