# Untitled

Sep 18th, 2023
1,579
0
1 day
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /**
2.  * Definition for a binary tree node.
3.  * struct TreeNode {
4.  *     int val;
5.  *     TreeNode *left;
6.  *     TreeNode *right;
7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10.  * };
11.  */
12. class Solution {
13.
14. private:
15.
16. int Travel(TreeNode* node, int Height = 0){
17.
18.
19.   if(node == nullptr){return Height;}
20.   ++Height; // высота текущего узла
21.
22.   int LeftHeight = Travel(node->left, Height);
23.   if(LeftHeight == -1){return -1;}
24.
25.   int RightHeight = Travel(node->right, Height);
26.   if(RightHeight == -1){return -1;}
27.
28.   cout << LeftHeight << ' ' << RightHeight << '\n';
29.   if(abs(RightHeight - LeftHeight) > 1){return -1;}
30.
31.   return max(LeftHeight, RightHeight) + 1;
32. }
33.
34. public:
35.     bool isBalanced(TreeNode* root) {
36.
37.       if(root == nullptr){return true;}
38.       return (Travel(root->left)  >= 0 && Travel(root->right) >= 0);
39.
40.     }
41. };