LeetCode: 257. 二叉树的所有路径
[力扣题目链接] https://leetcode.cn/problems/binary-tree-paths/
[《代码随想录》算法视频公开课] https://www.bilibili.com/video/BV1ZG411G7Dh
题解:
-
这一题使用了递归 + 回溯 ,并且使用了递归前中后序遍历中的前序遍历
-
因为前序遍历是 中左右一直往左边进行遍历,形成了一条path,之后把path加入到结果集中
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
/*
这一题使用了递归 + 回溯 ,并且使用了递归前中后序遍历中的前序遍历,因为前序遍历是 中左右
一直往左边进行遍历,形成了一条path,之后把path加入到结果集中
*/
class Solution {
private:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result) {
path.push_back(cur->val); // 中
if(cur->left == NULL && cur->right == NULL) {
string sPath;
for(int i = 0; i < path.size() - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
// 左
if(cur->left) {
traversal(cur->left, path, result);
path.pop_back();
}
// 右
if(cur->right) {
traversal(cur->right, path, result);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(root == NULL) return result;
traversal(root, path, result);
return result;
}
};