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 ret.clear(); 14 string s = ""; 15 if(root == NULL) return ret; 16 dfs(root, s); 17 for(int i = 0; i < ret.size(); ++i){ 18 ret[i].erase(ret[i].begin(), ret[i].begin() + 2); 19 } 20 return ret; 21 } 22 23 void dfs(TreeNode * root, string s) 24 { 25 stringstream ss; 26 ss << "->" << root->val; 27 s += ss.str(); 28 if(root->left == NULL && root->right == NULL){ 29 ret.push_back(s); 30 return; 31 } 32 if(root->left){ 33 dfs(root->left, s); 34 } 35 if(root->right){ 36 dfs(root->right, s); 37 } 38 } 39 private: 40 vector<string> ret; 41 };
时间: 2024-12-19 19:58:21