fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct TreeNode{
  5. int data;
  6. TreeNode* right;
  7. TreeNode* left;
  8. TreeNode(int val):left(nullptr),right(nullptr),data(val){};
  9. };
  10.  
  11. void helper(TreeNode* root,vector<int>&curr,vector<vector<int>>&ans){
  12. if(!root)return;
  13.  
  14. curr.push_back(root->data);
  15. if(!root->left && !root->right){
  16. ans.push_back(curr);
  17. }else{
  18. helper(root->left,curr,ans);
  19. helper(root->right,curr,ans);
  20. }
  21. curr.pop_back();
  22. }
  23. vector<vector<int>>print(TreeNode* root){
  24. vector<vector<int>>ans;
  25. if(!root)return ans;
  26.  
  27. vector<int>curr;
  28. helper(root,curr,ans);
  29. return ans;
  30. }
  31. TreeNode* buildTree(){
  32. int x;cin>>x;
  33. if(x == -1)return nullptr;
  34.  
  35. TreeNode* root = new TreeNode(x);
  36.  
  37. queue<TreeNode*>q;
  38. q.push(root);
  39.  
  40. while(!q.empty()){
  41. auto u= q.front();q.pop();
  42.  
  43. if(cin>>x && x!=-1){
  44. u->left = new TreeNode(x);
  45. q.push(u->left);
  46. }
  47.  
  48. if(cin>>x && x!=-1){
  49. u->right = new TreeNode(x);
  50. q.push(u->right);
  51. }
  52. }
  53. return root;
  54. }
  55. int main() {
  56. TreeNode* root = buildTree();
  57. vector<vector<int>>ans = print(root);
  58.  
  59. for(auto x : ans){
  60. for(int y : x){
  61. cout<<y<< " ";
  62. }
  63. cout<<endl;
  64. }
  65. return 0;
  66. }
Success #stdin #stdout 0s 5316KB
stdin
1 2 3 4 5 -1 -1
stdout
1 2 4 
1 2 5 
1 3