/** * @author johnsondu * @time 2015.8.21 16:30 * @description tranverse a tree * @url https://leetcode.com/problems/binary-tree-paths/ */ /** * 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: void tranverse(TreeNode *child, string str, vector<string> &vec) { if(str == "") str += to_string(child->val); else str += ("->" + to_string(child->val)); if(!child->left && !child->right) { vec.push_back(str); return; } if(child->left) tranverse(child->left, str, vec); if(child->right) tranverse(child->right, str, vec); } vector<string> binaryTreePaths(TreeNode* root) { TreeNode *head = root; vector<string> ans; if(!head) return ans; string cnt(""); tranverse(head, cnt, ans); return ans; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-06 19:36:46