Medium: Binary Tree Paths Add to List

来源:互联网 发布:淘宝网卖精密管违法吗 编辑:程序博客网 时间:2024/06/06 03:11
257. Binary Tree Paths Add to ListDescriptionHintsSubmissionsSolutionsTotal Accepted: 102130Total Submissions: 276990Difficulty: EasyContributor: LeetCodeGiven a binary tree, return all root-to-leaf paths.For example, given the following binary tree:   1 /   \2     3 \  5All root-to-leaf paths are:["1->2->5", "1->3"]

代码如下:

class Solution {public:    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类放于t中,再一个一个递归的压入result,再返回。
0 0
原创粉丝点击