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. bool sym(TreeNode* left,TreeNode* right){
  10. if(left == nullptr && right == nullptr)return true;
  11. if(left == nullptr || right == nullptr)return false;
  12.  
  13. if(left->val!=right->val)return false;
  14.  
  15. return sym(left->left,right->right)&&sym(left->right,right->left);
  16. }
  17. bool isSymm(TreeNode* root){
  18.  
  19. if(root == nullptr)return true;
  20. return sym(root->left,root->right);
  21.  
  22. }
  23. TreeNode* buildTree(){
  24. int x;cin>>x;
  25. if(x==-1)return nullptr;
  26. TreeNode* root = new TreeNode(x);
  27.  
  28. queue<TreeNode*>q;
  29. q.push(root);
  30.  
  31. while(!q.empty()){
  32. auto u = q.front();
  33. q.pop();
  34.  
  35. if(cin>>x && x!=-1){
  36. u->left = new TreeNode(x);
  37. q.push(u->left);
  38. }
  39.  
  40. if(cin>>x && x!=-1){
  41. u->right = new TreeNode(x);
  42. q.push(u->right);
  43. }
  44. }
  45. return root;
  46. }
  47. int main() {
  48. TreeNode* root = buildTree();
  49.  
  50. bool ans = isSymm(root);
  51. cout<<ans;
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 5288KB
stdin
1 2 2 -1 3 -1 3
stdout
Standard output is empty