平衡二叉树(LeetCode简单篇110题)

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
《平衡二叉树(LeetCode简单篇110题)》
解题思路:
用时间复杂度为O(n)的算法
先判断根结点,如果只有一个,则为1;
否则看左子树的深度减去右子树的深度等不等于1;
如果等于1,那么这颗二叉树就是平衡二叉树;
它的深度等于左右子数最大的深度+1;

bool _isBalanced(struct TreeNode* root,int* depth)
{
	if(root == NULL)
	{
		*depth = 0;
		return true;
	}
	int leftdepth = 0;
	int rightdepth = 0;
	if(_isBalanced(root->left,&leftdepth)&&
	   _isBalanced(root->right,&rightdepth)&&
	   abs(leftdepth - rightdepth) < 2)
	   {
	   		*depth = leftdepth > rightdepth ? leftdepth + 1 : rightdepth + 1;
	   		return true;
	   }
	else
	{
		return false;
	}
}
bool isBalanced(struct TreeNode* root)
{
	int depth = 0;
	return _isBalanced(root,&depth);
}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/ADream__/article/details/85859303
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞