leetcode Binary Tree Paths 257

来源:互联网 发布:可延迟服务器调度算法 编辑:程序博客网 时间:2024/06/05 14:54

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

题目链接

要找出所有的路径,考虑使用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 {private:    vector<string> vc;public:    vector<string> binaryTreePaths(TreeNode* root) {          vc.clear();          if(root==NULL) return vc;          string path=to_string(root->val);          dfs(root,path);          return vc;    }    void dfs(TreeNode* root,string s){          if(root->left==NULL && root->right==NULL) {            vc.push_back(s);            return;          }            if(root->left!=NULL) dfs(root->left,s+"->"+to_string(root->left->val));          if(root->right!=NULL) dfs(root->right,s+"->"+to_string(root->right->val));    }};
0 0