257. 二叉树的所有路径 - 力扣(LeetCode) (leetcode-cn.com)
二叉树所有路径
递归
- DFS
- 有 递归 就有 回溯
class Solution {
public:
void DFS(TreeNode* node, vector<int>& path, vector<string>& ans) {
// 压入当前访问点
path.push_back(node->val);
// 如果是叶子节点,则找到一条路径,保存下来
if (!node->left && !node->right) {
string result;
int len = path.size();
for (int i = 0; i < len - 1; i++) {
result += to_string(path[i]);
result += "->";
}
result += to_string(path[len - 1]);
ans.emplace_back(result);
}
// 如果不是叶子结点,则继续寻找
if (node->left) {
DFS(node->left, path, ans);
// 回溯
path.pop_back();
}
if (node->right) {
DFS(node->right, path, ans);
//回溯
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
vector<int> path;
if (!root) return ans;
DFS(root, path, ans);
return ans;
}
};
- 虽然代码量少,但没有显式体现回溯
- path是值传递,每次函数调用并未真正将结点保存,仅仅是打印出来。
class Solution {
public:
void DFS2(TreeNode* node, string path, vector<string>& ans) {
path += to_string(node->val);
if (!node->left && !node->right) {
ans.push_back(path);
return;
}
if (node->left) DFS2(node->left, path + "->", ans);
if (node->right) DFS2(node->right, path + "->", ans);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
// 变化点
string path;
if (!root) return ans;
DFS(root, path, ans);
return ans;
}
};
非递归
- 非递归前序遍历
- 仅修改处理部分内容即可
class Solution2 {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
stack<TreeNode*> stk;
// 比起遍历,多了保存遍历路径的栈
stack<string> pathStk;
if (!root) return ans;
stk.push(root);
pathStk.push(to_string(root->val));
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
if (node) {
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
stk.push(node);
stk.push(nullptr);
}
// 只需要修改处理部分的内容
else {
node = stk.top();
stk.pop();
// 弹出当前结点对应的路径
string path = pathStk.top();
pathStk.pop();
// 如果是叶子结点就保存答案
if (!node->right && !node->left) {
ans.push_back(path);
}
// 如果不是叶子结点,就处理剩下的路径
// 注意顺序是先压右再压左,因为我们的处理顺序如此
if (node->right)
pathStk.push(path + "->" + to_string(node->right->val));
if (node->left)
pathStk.push(path + "->" + to_string(node->left->val));
}
}
return ans;
}
};
int main() {
Solution* s = new Solution();
return 0;
}