您的位置:首页 > 其它

算法设计与应用基础: 第四周(1)

2017-03-15 23:46 363 查看


257. Binary Tree Paths

Add to List

DescriptionSubmissionsSolutions

Total Accepted: 96996
Total Submissions: 267457
Difficulty: Easy
Contributors: Admin

Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:

1
/   \
2     3
\
5

解题思路:
很直接的深度优先算法,但是要注意为了保存每天路径的string值,需要新设计一个函数(参数为需要返回的vector<string>,和此路径上的string值,和当前的节点指针)
代码如下
void binaryTreePaths(vector<string>& result, TreeNode* root, string t) {
if(!root->left && !root->right) {
result.push_back(t);
return;
}

if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val));
if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));
}

vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(!root) return result;

binaryTreePaths(result, root, to_string(root->val));
return result;
}

收获:string类可以直接相加,to_string()的用法以及设计新的辅助函数来更好的实现功能 使得代码简洁。(也是递归的调用)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: