原文题目:
读题:
题目意思很简单,就是将二叉树从根节点到叶节点的所有路径用字符串表示,同时存在一个数组中。
解题思路:
二叉树就用递归思想,若先根节点,然后遍历左子树,然后遍历右子树,当节点很多时,递归次数较多,
以下是AC代码:
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class Solution
{
public:
void getResult(TreeNode *root,string str, vector<string> &vec)
{
if(str.empty()) str += to_string(root->val);
else str += ("->" + to_string(root->val));
if((!root->left)&&(!root->right))
{
vec.push_back(str);
return;
}
if(root->left) getResult(root->left,str,vec);
if(root->right) getResult(root->right,str,vec);
}
vector<string> binaryTreePaths(TreeNode *root)
{
vector <string> result;
if(!root) return result;
string str = "";
getResult(root,str,result);
return result;
}
};