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

来源:互联网 发布:淘宝一键模板 编辑:程序博客网 时间:2024/06/03 15:41

257. Binary Tree Paths

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()的用法以及设计新的辅助函数来更好的实现功能 使得代码简洁。(也是递归的调用)


0 0
原创粉丝点击