二叉树所有路径
思路:用一個path變量保存一條路徑,判斷標準是否是葉子節點。注意一點vector類似于int,如果想要按地址傳遞參數的話,需要加&變成引用,將int轉換為string用to_string()函數。
class Solution {
public:
? ? void allpath(TreeNode *root,string path,vector<string> &paths){
? ? ? ?
? ? ? ? if(root!=NULL){
? ? ? ? ? ??
? ? ? ? ? ? ?path+=to_string(root->val);
? ? ? ? if(root->left==NULL&&root->right==NULL){
? ? ? ? ? ? paths.push_back(path);
? ? ? ? }
? ? ? ? else{
? ? ? ? ? ? path+="->";
? ? ? ? ? ? allpath(root->left,path,paths);
? ? ? ? ? ? allpath(root->right,path,paths);
? ? ? ? }
? ? ? ? }
? ? ? ?
? ? ? ?
? ? }
? ? vector<string> binaryTreePaths(TreeNode* root) {
? ? ? vector<string> paths;
? ? ??
? ? ? ? if(root!=NULL){
? ? ? ? ? ? allpath(root,"",paths);
? ? ? ? }
? ? ? ? return paths;
? ? }
};
總結