題目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]題目鏈接
題意:
給一棵二叉樹,要求求出所以從根到葉的路徑,並將路徑壓入vector中返回。
普通先序遍歷的基礎上,每到一個節點,進行判斷是否爲葉子結點,假如是葉子結點,那麼就將path壓入vector,否則,將當前path遞歸進下一層。
代碼如下;
class Solution {
public:
vector<string> ans;
void dfs(TreeNode* node, string path) {
path += to_string(node->val);
if (!node->left && !node->right) {
ans.push_back(path);
return;
}
path += "->";
if (node->left) {
dfs(node->left, path);
}
if (node->right) {
dfs(node->right, path);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return ans;
dfs(root, "");
return ans;
}
};