解法1:递归法
/**
* 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) {}
* };
*/
class Solution {
public:
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();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(root == NULL) return result;
traversal(root,path,result);
return result;
}
};
解法2:迭代法
/**
* 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) {}
* };
*/
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* node = treeSt.top();
treeSt.pop();
string path = pathST.top();
pathST.pop();
if(node->left == NULL && node->right == NULL) {
result.push_back(path);
}
if(node->right){
treeSt.push(node->right);
pathST.push(path + "->" + to_string(node->right->val));
}
if(node->left){
treeSt.push(node->left);
pathST.push(path + "->" + to_string(node->left->val));
}
}
return result;
}
};