所谓平衡二叉树是指任意子树的高度差不超过1 目前所学习的有关二叉树的问题,都是基于二叉树的遍历顺序来实现的
# include <iostream>
# include <sstream>
# define LEN 10009
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode ( ) : val ( 0 ) , left ( nullptr ) , right ( nullptr ) { }
TreeNode ( int v) : val ( v) , left ( nullptr ) , right ( nullptr ) { }
TreeNode ( int v, TreeNode* l, TreeNode* r) : val ( v) , left ( l) , right ( r) { }
} ;
class Solution {
public :
TreeNode* getTree ( ) {
TreeNode* tnArr[ LEN] { nullptr } ;
std:: string str_content;
std:: getline ( std:: cin, str_content) ;
std:: stringstream ss { str_content} ;
for ( int index = 0 ; ss >> str_content; ++ index) {
if ( str_content != "null" )
tnArr[ index] = new TreeNode ( stoi ( str_content) ) ;
else
tnArr[ index] = nullptr ;
if ( index > 0 ) {
if ( index % 2 == 1 )
tnArr[ index / 2 ] -> left = tnArr[ index] ;
else
tnArr[ ( index - 1 ) / 2 ] -> right = tnArr[ index] ;
}
}
return tnArr[ 0 ] ;
}
bool isBalanced ( TreeNode* root) {
if ( getHeight ( root) != - 1 )
return true ;
return false ;
}
int getHeight ( TreeNode* node) {
if ( node == nullptr )
return 0 ;
int left_height = getHeight ( node-> left) ;
if ( left_height == - 1 )
return - 1 ;
int right_height = getHeight ( node-> right) ;
if ( right_height == - 1 )
return - 1 ;
if ( std:: abs ( left_height - right_height) > 1 )
return - 1 ;
return 1 + std:: max ( left_height, right_height) ;
}
} ;
int main ( )
{
Solution s;
TreeNode* root = s. getTree ( ) ;
std:: cout << s. isBalanced ( root) << std:: endl;
return 0 ;
}