原题:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
题意是求出所有二叉树到叶子节点的路径并且以string的形式输出,典型的先序遍历,最蠢的是你还要用'->'表示相连,正好看了stringstream转化int为stream可以利用一下,另外由于循环调用压栈时不好记忆当前路径(其实也行不过还需要一个vector容器,浪费不少空间),就使用递归了,结果:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Paths.
Memory Usage: 12 MB, less than 45.45% of C++ online submissions for Binary Tree Paths.
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> ans;
vector<string> binaryTreePaths(TreeNode* root) {
if(root==nullptr){return ans;}
btp(root,"");
return ans;
}
void btp(TreeNode* root,string path){
stringstream ss;
ss<<root->val;
string temp;
ss>>temp;
path+=temp;
if(root->left==nullptr&&root->right==nullptr){
ans.push_back(path);
}
path+='-';
path+='>';
if(root->left!=nullptr){btp(root->left,path);}
if(root->right!=nullptr){btp(root->right,path);}
}
};
为了减少内存消耗,还是写了循环调用。循环需要三个vector,一个用来返回结果,一个用来压栈时记忆路径,一个用来压栈,结果:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Paths.
Memory Usage: 9.8 MB, less than 99.55% of C++ online submissions for Binary Tree Paths.
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if(root==nullptr){return ans;}
vector<string> path;
vector<TreeNode*> lib;
path.push_back("");
lib.push_back(root);
while(!lib.empty()){
TreeNode *cur=lib.back();
lib.pop_back();
string temp=path.back();
path.pop_back();
stringstream ss;
ss<<cur->val;
string s;
ss>>s;
temp+=s;
if(cur->left==nullptr&&cur->right==nullptr){
ans.push_back(temp);
continue;
}
temp+="->";
if(cur->left!=nullptr){
lib.push_back(cur->left);
path.push_back(temp);
}
if(cur->right!=nullptr){
lib.push_back(cur->right);
path.push_back(temp);
}
}
return ans;
}
};