leetcode 257. Binary Tree Paths
自己写的一个代码,注意这里判断是否是根节点前,应该把当前节点的value值push_back到res中
/** * 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<int> res; vector<vector<int>> result; binary(root,res,result); vector<string> str; for(int i = 0;i < result.size();i++){ string tmp; for(int j = 0;j < result[i].size();j++){ tmp += to_string(result[i][j]); tmp += "->"; } str.push_back(tmp.substr(0,tmp.size() - 2)); } return str; } void binary(TreeNode* root,vector<int> res,vector<vector<int>>& result){ if(!root) return; res.push_back(root->val); if(!root->left && !root->right){ result.push_back(res); return; } binary(root->left,res,result); binary(root->right,res,result); } };