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"]题意:返回二叉树的路径。
思路:那就返回呗。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root == NULL)
return res;
binaryTreePaths(root, to_string(root->val), res);
return res;
}
private:
void binaryTreePaths(TreeNode* root, string cur, vector<string>& res){
if (root->left == NULL && root->right==NULL){
res.push_back(cur);
return;
}
cur += "->";
if (root->left)
binaryTreePaths(root->left, cur+to_string(root->left->val), res);
if (root->right)
binaryTreePaths(root->right, cur+to_string(root->right->val), res);
}
};