简单的一批 我都不想写了。。。。 广度或深度遍历
/** * 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==NULL){ return ans; } string s=""; dfs(ans,root,s); return ans; } void dfs(vector<string> &ans,TreeNode* root,string s){ if(root->left==NULL&&root->right==NULL){ s+=to_string(root->val); ans.push_back(s); }else{ s+=(to_string(root->val)+"->"); if(root->left!=NULL){ dfs(ans,root->left,s); } if(root->right!=NULL){ dfs(ans,root->right,s); } } } }; class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; if(root==NULL){ return ans; } queue<TreeNode*> que; queue<string> path; que.push(root); path.push(""); while(!que.empty()){ TreeNode* t=que.front(); string s=path.front(); que.pop(); path.pop(); if(t->left==NULL&&t->right==NULL){ s+=to_string(t->val); ans.push_back(s); }else{ s+=(to_string(t->val)+"->"); if(t->left!=NULL){ que.push(t->left); path.push(s); } if(t->right!=NULL){ que.push(t->right); path.push(s); } } } return ans; } };