We know that the balanced binary tree requires that the left and right subtree of the binary tree is not more than 1, that is, the value is { -1,0,1}, while the empty tree is also a balanced binary tree, know these, we can easily carry out the balance of the binary tree, the implementation code as follows:
A function that defines the depth of a tree, we define it by recursion, and then we define a function that determines whether the tree is a balanced binary tree, also uses a recursive definition, because the left and right subtree of the balanced binary tree must be a balanced binary tree.
Class Solution {public
:
bool isbalanced (TreeNode *root) {
if (!root) return true;
else return (ABS (Depth (root->left)-depth (root->right) <2) &&isbalanced (root->left) && Isbalanced (root->right);
}
int depth (treenode* root) {
if (!root) return 0;
if (!root->left&&!root->right) return 1;
int left=depth (root->left) +1;
int right=depth (root->right) +1;
Return Max (left,right);
}
;