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.
Subscribe to see which companies asked this question
分析:
以下是错误答案。通过201/226个案例!
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode* node) { if(node==NULL) return 0; return 1+max(maxDepth(node->left),maxDepth(node->right)); } bool isBalanced(TreeNode* root) { if(root==NULL) return true; if(abs(maxDepth(root->left) - maxDepth(root->right)) > 1)//最高根的左子树和右子树节点高度差不能超过1 return false; return true; } };
修改代码后(注意,依然错误):通过案例,218/226
这一次真不知道错在哪里了!
class Solution { public: int maxDepth(TreeNode* node) { if(node==NULL) return 0; return 1+max(maxDepth(node->left),maxDepth(node->right)); } int minDepth(TreeNode* node) { if(node==NULL) return 0; return 1+min(minDepth(node->left),minDepth(node->right)); } bool isBalanced(TreeNode* root) { if(root==NULL) return true; int maxleft = maxDepth(root->left); int maxright = maxDepth(root->right); int minright = minDepth(root->right); int minleft = minDepth(root->left); if(abs(maxleft-minright) > 1)//高度差不能超过1 return false; if(abs(maxright-minleft) > 1)//高度差不能超过1 return false; if(abs(maxleft-minleft) > 1)//高度差不能超过1 return false; if(abs(maxright-minleft) > 1)//高度差不能超过1 return false; return true; } };
参考别人的分析:
题意:
给定一棵二叉树,判断是否是高度平衡的。
高度平衡的意思是,对于每一个节点,左子树跟右子树的高度最多相差1。
思路:
先写一个求高度的函数,递归的求该节点的高度,height(root) = 1 + max(height(root->left),height(root->right))。然后递归判断是否高度平衡,如果当前节点的左子树右子树高度相差小于1,那么递归判断左孩子与右孩子是否满足高度平衡。
以上。
代码如下:
class Solution { public: bool isBalanced(TreeNode* root) { if(root == NULL)return true; int diff = depth(root->left) - depth(root->right); if( diff >= -1 && diff <= 1) return isBalanced(root->left) && isBalanced(root->right); else return false; } int depth(TreeNode* root){ if(root == NULL) return 0; else return max(depth(root->left),depth(root->right)) + 1; } };
class Solution { public: bool isBalanced(TreeNode* root) { if(root == NULL)return true; return (checkHeight(root) > 0); } int checkHeight(TreeNode* root) { if(root == NULL) return 0; int left = checkHeight(root->left); if(left == -1) return -1; int right = checkHeight(root->right); if(right == -1) return -1; int diff = left - right; if(diff > 1 || diff < -1) return -1; return max(left, right) + 1; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50811950
原作者博客:http://blog.csdn.net/ebowtang
本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895
参考资源:
【1】博客地址,http://blog.csdn.net/u014673347/article/details/46707609