Leetcode63: Binary Tree Paths

来源:互联网 发布:协同过滤推荐算法综述 编辑:程序博客网 时间:2024/06/08 07:33

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void dfs(TreeNode* Node, string item, vector<string>& result)    {        if(Node == NULL)            return;        item = item + std::to_string(Node->val);        if(Node->left)            dfs(Node->left, item+"->", result);        if(Node->right)            dfs(Node->right, item+"->", result);        if(!Node->left && !Node->right)            result.push_back(item);    }    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> str;        if(root == NULL)            return str;        dfs(root, "", str);        return str;    }};


0 0
原创粉丝点击