问题描述
笔记
代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string> res;
if (root == NULL)
return res;
string s = to_string(root->val);
getPath(root, s, res);
return res;
}
void getPath(TreeNode* root, string s, vector<string>& res)
{
if (root->left != NULL)
{
string left = s + "->" + to_string(root->left->val);
getPath(root->left, left, res);
}
if (root->right != NULL)
{
string right = s + "->" + to_string(root->right->val);
getPath(root->right, right, res);
}
if (root->left == NULL && root->right == NULL)
{
res.push_back(s);
}
}
};
二战
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
string s = "";
vector<string> res;
getPath(root, s, res);
return res;
}
void getPath(TreeNode *root, string s, vector<string> &res)
{
if (root == NULL)
{
return;
}
s += to_string(root->val);
if (root->left == NULL && root->right == NULL)
{
res.push_back(s);
return;
}
s += "->";
if (root->left != NULL)
{
getPath(root->left, s, res);
}
if (root->right != NULL)
{
getPath(root->right, s, res);
}
}
};