leetcode--257.Binary Tree Paths

使用深度优先搜索的方法遍历每一条枝,遍历完的终止条件为左右子树都为空,这时候将这条枝的string 插入vector 中。

class Solution {
public:
// vector 一直插入string,所以为引用类型,string不能是引用类型
void dfs(TreeNode *root, vector<string> & result, string temp)
{
if(root->left==NULL&&root->right==NULL)
result.push_back(temp);
if(root->left)
dfs(root->left,result,temp+"->"+to_string(root->left->val));
if(root->right)
dfs(root->right,result,temp+"->"+to_string(root->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>result;
if(root==NULL)
return result;
string temp=to_string(root->val);
dfs(root, result, temp);
return result;
}
};
第二种方法,在函数内部进行递归:

vector<string> binaryTreePaths(TreeNode *root)
{
vector<string> result;
if(root==NULL)
return result;
if(root->left==NULL&& root->right==NULL)
return {to_string(root->val)};
vector<string> left=binaryTreePaths(root->left);
vector<string> right=binaryTreePaths(root->right);
left.insert(left.end(),right.begin(),right.end());
vector<string>::iterator iter;
for(iter=left.begin();iter!=left.end();iter++)
{
*iter=to_string(root->val)+"->"+*iter;
}
return left;
}

浙公网安备 33010602011771号