平衡二叉树
int MAX ( int a, int b)
{ return a > b ? a : b;
}
int getHeight ( struct TreeNode * root) { if ( root == NULL ) { return 0 ; } int left = getHeight ( root-> left) ; int right = getHeight ( root-> right) ; return MAX ( left, right) + 1 ;
}
bool isBalanced ( struct TreeNode* root) { if ( root == NULL ) { return true; } bool is_left_balance = isBalanced ( root-> left) ; if ( is_left_balance == false) { return false; } bool is_right_balance = isBalanced ( root-> right) ; if ( is_right_balance == false) { return false; } int left_height = getHeight ( root-> left) ; int right_height = getHeight ( root-> right) ; int diff = left_height- right_height; if ( diff >= - 1 && diff <= 1 ) { return true; } else { return false; }
}
根据二叉树创建字符串
class Solution {
public : string tree2str ( TreeNode* t) { if ( t== nullptr ) return "" ; stringstream ss; function< void ( TreeNode* ) > helper = [ & ss, & helper] ( TreeNode* t) { ss<< t- > val; if ( t- > left== nullptr ) { if ( t- > right!= nullptr ) { ss<< "()(" ; helper ( t- > right) ; ss<< ')' ; } } else if ( t- > right== nullptr ) { ss<< '(' ; helper ( t- > left) ; ss<< ')' ; } else { ss<< '(' ; helper ( t- > left) ; ss<< ")(" ; helper ( t- > right) ; ss<< ')' ; } } ; helper ( t) ; string s; ss>> s; return s; }
} ;