https://leetcode.com/problems/binary-tree-paths/description/
給二元樹的 root ,回傳所有 root 到 leaf 的路徑 (任意順序)
這題很簡單,就用一個 string path 來記錄路徑
走到 leaf 再塞進 ans 裡
至於走法,就用遞迴一直往左往右,沒什麼好說的
class Solution
{
public:
vector<string> binaryTreePaths(TreeNode *root)
{
vector<string> ans;
helper(root, "", ans);
return ans;
}
private:
void helper(TreeNode *node, string path, vector<string> &ans)
{
if (!node)
return;
if (!path.empty())
path += "->";
path += to_string(node->val);
if (!node->left && !node->right)
{
ans.emplace_back(path);
return;
}
helper(node->left, path, ans);
helper(node->right, path, ans);
}
};
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up