Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree:
All root-to-leaf paths are:[“1->2->5”, “1->3”]
分析
深度搜索
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ret;
string str;
dfs(ret, str, root);
return ret;
}
void dfs(vector<string>& ret, string& str, TreeNode* root){
if (!root)
return;
if (root && !root->left&&!root->right){
str+=to_string(root->val);
ret.push_back(str);
return;
}
string tmp = str;
str += to_string(root->val)+"->";
if (root->left)
dfs(ret, str, root->left);
str = tmp;
tmp = str;
str += to_string(root->val) + "->";
if (root->right)
dfs(ret, str, root->right);
str=tmp;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lmingyin5/article/details/47726725