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