Q: 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 ofevery node never differ by more than 1.
判断一个二叉树是否高度平衡:对任意结点,其左右子树的高度差<=1.
A: 递归的对每个结点做判断是否平衡。子树的height<0,表示该子树不平衡。
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return (getHeight(root)>=0)? true: false;
}
int getHeight(TreeNode *root)
{
if(!root) return 0;
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
if(leftHeight<0||rightHeight<0||abs(leftHeight-rightHeight)>1) //该子树不平衡,返回-1
return -1;
else
return max(leftHeight,rightHeight)+1;
}
而以下这种方法,计算子树的高度也是递归的,导致重复的访问结点。所以将高度作为返回值,同时-1做为不平衡子树的flag,减少了结点的重复访问。O(N)
public boolean isBalanced(TreeNode root) { if (root == null) return true; int left = getHeight(root.left); int right = getHeight(root.right); if (Math.abs(left - right) > 1) return false; return isBalanced(root.left) && isBalanced(root.right); } private int getHeight(TreeNode n) { if (n == null) return 0; return Math.max(getHeight(n.left), getHeight(n.right)) + 1; }
原文链接: https://www.cnblogs.com/summer-zhou/archive/2013/06/04/3117074.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/91131
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!