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 dfs(TreeNode* root){
  10. if(root == nullptr)return 0;
  11. int left = dfs(root->left);
  12. if(left == -1)return -1;
  13. int right = dfs(root->right);
  14. if(right == -1)return -1;
  15. if(abs(left-right)>1)return -1;
  16. return 1+max(left,right);
  17. }
  18. bool balanced(TreeNode* root){
  19. return dfs(root)!=-1;
  20. }
  21.  
  22. TreeNode* buildTree(){
  23. int x;cin>>x;
  24. if(x==-1)return nullptr;
  25. TreeNode* root = new TreeNode(x);
  26. queue<TreeNode*>q;
  27. q.push(root);
  28.  
  29. while(!q.empty()){
  30. auto u = q.front();
  31. q.pop();
  32.  
  33. if(cin>>x && x!=-1){
  34. u->left = new TreeNode(x);
  35. q.push(u->left);
  36. }
  37.  
  38. if(cin>>x && x!=-1){
  39. u->right = new TreeNode(x);
  40. q.push(u->right);
  41. }
  42. }
  43. return root;
  44. }
  45. int main() {
  46. TreeNode*root = buildTree();
  47. cout << (balanced(root) ? "true" : "false") << "\n";
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5320KB
stdin
3 9 20 -1 -1 15 7
stdout
true