(leetcode)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"]
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<string> binaryTreePaths(TreeNode* root) { 13 if(!root) return vector<string>(); 14 vector<string> res; 15 string s; 16 DFS(root,to_string(root->val),res); 17 return res; 18 19 } 20 void DFS(TreeNode* root,string s,vector<string>& res) 21 { 22 if(!root->left && !root->right) res.push_back(s); 23 if(root->left) DFS(root->left,s+"->"+to_string(root->left->val),res); 24 if(root->right) DFS(root->right,s+"->"+to_string(root->right->val),res); 25 } 26 };

浙公网安备 33010602011771号