c++
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root == nullptr)
return res;
getLeafpath(res, root, toString(root->val));
return res;
}
private:
void getLeafpath(vector<string> &res, TreeNode* root, string path) {
if (root->left == nullptr && root->right == nullptr) {
res.push_back(path);
return;
}
if(root->left != nullptr)
getLeafpath(res, root->left, path + "->" + toString(root->left->val));
if (root->right != nullptr)
getLeafpath(res, root->right, path + "->" + toString(root->right->val));
}
string toString(const int &value) {
stringstream ss;
ss << value;
return ss.str();
}
};
python
class Solution:
def binaryTreePaths(self, root):
res = []
if not root:
return res
self.getLeafpath(res, root, str(root.val))
return res
def getLeafpath(self, res, root, path):
if not root.left and not root.right:
res.append(path)
if root.left:
self.getLeafpath(res, root.left, path + '->' + str(root.left.val))
if root.right:
self.getLeafpath(res, root.right, path + '->' + str(root.right.val))