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