leetcode 257. Binary Tree Paths

£神魔★判官ぃ 2021-11-11 10:36 258阅读 0赞

自己写的一个代码,注意这里判断是否是根节点前,应该把当前节点的value值push_back到res中

  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. vector<int> res;
  14. vector<vector<int>> result;
  15. binary(root,res,result);
  16. vector<string> str;
  17. for(int i = 0;i < result.size();i++){
  18. string tmp;
  19. for(int j = 0;j < result[i].size();j++){
  20. tmp += to_string(result[i][j]);
  21. tmp += "->";
  22. }
  23. str.push_back(tmp.substr(0,tmp.size() - 2));
  24. }
  25. return str;
  26. }
  27. void binary(TreeNode* root,vector<int> res,vector<vector<int>>& result){
  28. if(!root)
  29. return;
  30. res.push_back(root->val);
  31. if(!root->left && !root->right){
  32. result.push_back(res);
  33. return;
  34. }
  35. binary(root->left,res,result);
  36. binary(root->right,res,result);
  37. }
  38. };

转载于:https://www.cnblogs.com/ymjyqsx/p/11298093.html

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读