题意描述:
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
需要利用回溯,要把每一条路径记录下来。回溯过程如图所示:
需要注意,写代码的事需要将回溯和递归写在同一个花括号。
递归法C++代码如下:
class Solution {
private:
void travelsal(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++) { // 将path里记录的路径转为string格式
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return ;
}
if(cur->left){
travelsal(cur->left, path, result);
path.pop_back(); //回溯
}
if(cur->right){
travelsal(cur->right, path, result);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(root == NULL){
return result;
}
travelsal(root, path, result);
return result;
}
};
迭代法C++代码如下:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode*> treeSt;// 保存树的遍历节点
stack<string> pathSt; // 保存遍历路径的节点
vector<string> result; // 保存最终路径集合
if(root == NULL){
return result;
}
treeSt.push(root);
pathSt.push(to_string(root->val));
while(!treeSt.empty()){
TreeNode* cur = treeSt.top();
treeSt.pop();
string path = pathSt.top();
pathSt.pop();
if(cur->left == NULL && cur->right == NULL){
result.push_back(path);
}
if(cur->right){
treeSt.push(cur->right);
pathSt.push(path + "->" + to_string(cur->right->val));
}
if(cur->left){
treeSt.push(cur->left);
pathSt.push(path + "->" + to_string(cur->left->val));
}
}
return result;
}
};