fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5. public:
  6. int data;
  7. Node *left, *right;
  8. Node(int data){
  9. this->data = data;
  10. this->left = this->right = NULL;
  11. }
  12. };
  13.  
  14. int leftHeight(Node* node){
  15. int h=0;
  16. while(node){
  17. h++;
  18. node = node->left;
  19. }
  20. return h;
  21. }
  22.  
  23. int rightHeight(Node* node){
  24. int h=0;
  25. while(node){
  26. h++;
  27. node = node->right;
  28. }
  29. return h;
  30. }
  31.  
  32. int countNodes(Node* root){
  33. if(!root)
  34. return 0;
  35. int lh = leftHeight(root);
  36. int rh = rightHeight(root);
  37. if(lh==rh)
  38. return (1<<lh)-1;
  39. return countNodes(root->left)+countNodes(root->right)+1;
  40. }
  41.  
  42.  
  43. int main() {
  44. Node* root = new Node(1);
  45. root->left = new Node(2);
  46. root->right = new Node(3);
  47. root->left->left = new Node(4);
  48. root->left->right = new Node(5);
  49. root->right->left = new Node(6);
  50. root->right->right = new Node(7);
  51. root->left->left->left = new Node(8);
  52. root->left->left->right = new Node(9);
  53. root->left->right->left = new Node(10);
  54. cout<<countNodes(root)<<endl;
  55. return 0;
  56. }
Success #stdin #stdout 0s 4172KB
stdin
Standard input is empty
stdout
10