简单的前序遍历
cppclass Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths; // 存储所有路径的结果数组
string path; // 当前路径的字符串
dfs(root, path, paths); // 深度优先搜索
return paths;
}
private:
void dfs(TreeNode* node, string path, vector<string>& paths) {
if (node == nullptr) return; // 递归终止条件
path += to_string(node->val); // 将当前节点的值添加到路径字符串中
if (node->left == nullptr && node->right == nullptr) {
paths.push_back(path); // 如果是叶子节点,将路径添加到结果数组中
} else {
path += "->"; // 如果不是叶子节点,在路径字符串中添加箭头符号
dfs(node->left, path, paths); // 递归遍历左子树
dfs(node->right, path, paths); // 递归遍历右子树
}
}
};
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!