給一棵二叉樹,找出從根節(jié)點到葉子節(jié)點的所有路徑。
您在真實的面試中是否遇到過這個題? Yes
樣例
給出下面這棵二叉樹:
1
/ \
2 3
\
5
所有根到葉子的路徑為:
[
"1->2->5",
"1->3"
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string> results;
vector<int> temp;
if(root==NULL) {
return results;
}
preTravel(root,temp,results);
return results;
}
void preTravel(TreeNode* root,vector<int> &temp,vector<string> &results) {
temp.push_back(root->val);
if(root->left == NULL&&root->right == NULL) {
string str;
for(auto i: temp){
str += to_string(i) + "->";
}
str = str.substr(0,str.size()-2);
results.push_back(str);
}
if (root->left != NULL) {
preTravel(root->left,temp,results);
}
if (root->right != NULL) {
preTravel(root->right,temp,results);
}
temp.pop_back();
}
};
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。