[LeetCode] 110. Balanced Binary Tree 解题思路

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

问题:给定一个二叉树,判断其是否平衡。

当二叉树中所有节点的左右子树高度差不大于 1 时,这个二叉树视为平衡二叉树。

解题思路应该算一种分治思想。根据定义,递归地判断,实现判断。

     const int unbalanceKids = -;

     /**
* count the number of children of node and itself
*/
int height(TreeNode* node){ int heightL = ;
if (node->left != NULL){
heightL = height(node->left);
} if(heightL == unbalanceKids){
return unbalanceKids;
} int heightR = ;
if (node->right != NULL){
heightR = height(node->right);
} if(heightR == unbalanceKids){
return unbalanceKids;
} if (abs(heightL - heightR) > ){
return unbalanceKids;
} return max(heightL, heightR) + ;
} bool isBalanced(TreeNode* root) { if (root == NULL){
return true;
} int res = height(root);
if (res == unbalanceKids){
return false;
} return true;
}
上一篇:读书笔记-《Maven实战》-关于Maven依赖传递的思考 2018/4/26


下一篇:Confluence 6 开始编辑 CSS