[leetcode]257. Binary Tree Paths

来源:互联网 发布:js setdata 编辑:程序博客网 时间:2024/05/20 09:23

题目来源:https://leetcode.com/problems/binary-tree-paths/

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"]

方法一:

class Solution {public:    vector<string> binaryTreePaths(TreeNode *root)    {        std::vector<int> path;        std::vector<std::vector<int>> result;        std::vector<std::string> rec;        if(root==NULL)            return rec;        preTraverse(root, path, result);        for(std::vector<int> tmp:result)        {            std::string s(std::to_string(tmp[0]));            for(int i=1;i<tmp.size();i++)                s=s+"->"+std::to_string(tmp[i]);            rec.push_back(s);                    }        return rec;            }        void preTraverse(TreeNode *root,std::vector<int> path,std::vector<std::vector<int>> &result)    {                if(root==NULL)            return;        path.push_back(root->val);        if(root->left==NULL && root->right==NULL)        {            result.push_back(path);            return;        }        if(root->left)        preTraverse(root->left,path,result);        if(root->right)        preTraverse(root->right,path,result);        path.pop_back();                            }

 方法二:

class Solution{public:    vector<string> binaryTreePaths(TreeNode * root)    {        vector<string> res;        if(root)            dfs(root,"",res);        return res;    }        void dfs(TreeNode *root,string out,vector<string> &res)    {        out+=to_string(root->val);        if(root->left==NULL && root->right==NULL)            res.push_back(out);        else        {            if(root->left)                dfs(root->left,out+"->",res);            if(root->right)                dfs(root->right,out+"->",res);        }    }};


0 0
原创粉丝点击