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