Binary Tree Paths
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 {
private:
void binaryTreePaths(TreeNode* root, string path, vector<string> &result) {
if (root == NULL) return;
ostringstream oss;
oss << root->val;
path += oss.str();
if (root->left == NULL && root->right == NULL) {
result.push_back(path);
return;
}
path += "->";
binaryTreePaths(root->left, path, result);
binaryTreePaths(root->right, path, result);
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
binaryTreePaths(root, "", result);
return result;
}
};