题目描述链接:https://leetcode-cn.com/problems/binary-tree-paths/
基本思路:从根节点一直向下深搜即可。当访问到叶子节点时结束。记录一下,可以使用to_string()函数隶属于string头文件,将int转换为string。具体LeetCode代码如下:
/** * 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>res; vector<string> binaryTreePaths(TreeNode* root) { string path=""; dfs(root,path); return res; } void dfs(TreeNode* root,string path){ if(!root){//防止整个树为空或者 非叶子节点只有一个子树的情况 return; } if(!root->left&&!root->right){ path+=to_string(root->val); res.push_back(path); return ; } path+=to_string(root->val); path+="->"; dfs(root->left,path); dfs(root->right,path); } };