Binary Tree Paths
将二叉树中所有从根节点到叶子节点的路径以字符串的形式输出出来
直接遍历即可,注意只有左右子节点都是空节点时才叫叶子节点
代码如下
/**
* 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;
string path("");
findPaths(root, path, res);
return res;
}
private:
void findPaths(TreeNode* root, string path, vector<string>& res)
{
if(!root) return;
//to_string: 数字转字符串
path += to_string(root->val);
if(!root->left && !root->right)
res.emplace_back(path);
findPaths(root->left, path + "->", res);
findPaths(root->right, path + "->", res);
}
};