257. Binary Tree Paths
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { vector<string> res; void helper(TreeNode* node, string path) { if(!node->left and !node->right) res.push_back(path); else { if(node->left) helper(node->left, path + "->" + to_string(node->left->val)); if(node->right) helper(node->right, path + "->" + to_string(node->right->val)); } } public: vector<string> binaryTreePaths(TreeNode* root) { if(!root) return {}; helper(root, to_string(root->val)); return res; } };
|