题目:打印二叉树的所有路径
分析:就是深度遍历呗。注意对第一个节点做处理,不用打->,然后就完了
答案:
/**
* 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 {
private:
vector<string> res;
bool isStart = true;
void printTree(TreeNode* root, string temp){
if (!root)
return;
else{
stringstream ss;
string vals;
ss<<root->val;
ss>>vals;
if (isStart){
isStart = false;
temp = temp + vals;
}
else
temp = temp + "->" + vals;
if (root->left == NULL && root->right == NULL){
res.push_back(temp);
return;
}
printTree(root->left, temp);
printTree(root->right, temp);
}
};
public:
vector<string> binaryTreePaths(TreeNode* root) {
string temp = "";
if (!root)
return res;
else
printTree(root,temp);
return res;
}
};
扩展:用stringstream转换int和string类型。