257 Binary Tree Paths

来源:互联网 发布:yy免费协议软件 编辑:程序博客网 时间:2024/06/05 07:57

题意:给定二叉树,找出所有根到叶子的路径

分析:dfs.

代码:

/** * 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:    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> ans;        //if(root==nullptr)  return ans;        string curPath="";        dfs(ans,curPath,root);        return ans;    }    string getstring ( const int n ){        std::stringstream newstr;        newstr<<n;        return newstr.str();    }    void dfs(vector<string> &paths,string curPath,TreeNode* root){        if(root==nullptr)  return;        if(root->left==nullptr&&root->right==nullptr){            paths.push_back(curPath+getstring(root->val));            return;        }        dfs(paths,curPath+getstring(root->val)+"->",root->left);        dfs(paths,curPath+getstring(root->val)+"->",root->right);    }};


0 0
原创粉丝点击