题目:
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"]
思路:
这也是一道DFS的题目,关键是要判断出来一个结点是不是叶子结点。
代码:
/**
* 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) {
if(root == NULL) {
return {};
}
vector<string> ret;
string line;
binaryTreePaths(root, ret, line);
return ret;
}
private:
void binaryTreePaths(TreeNode* root, vector<string>& ret, string line) {
if(line.size() > 0) {
line += "->";
}
line += to_string(root->val);
if(root->left == NULL && root->right == NULL) {
ret.push_back(line);
return;
}
if(root->left) {
binaryTreePaths(root->left, ret, line);
}
if(root->right) {
binaryTreePaths(root->right, ret, line);
}
}
};