LeetCode | 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.

思路:height-balanced tree 是平衡二叉树,又称AVL树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是二叉树,且左子树和右子树的深度之差的绝对值不超过1。即,深度差值只能去-1,0,1。

因此,对于每个结点,先求它左子树及右子树的深度值。如果左、右子树深度差值符合要求,继续判断它的左子树和右子树是否为平衡二叉树,否则就不是平衡二叉树。

struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

class Solution 
{
public:
    bool isBalanced(TreeNode *root) 
	{
		if(!root)
			return true;
		else
			if(judge(maxDepth(root->left), maxDepth(root->right)))//判断当前结点的左右子树深度差值是否符合要求
				return isBalanced(root->left) && isBalanced(root->right);//继续判断它的左子树和右子树
			else
				return false;
	}

	bool judge(int L, int R)//左右子树深度差值的要求
	{
		if(L-R==0 || L-R==1 || L-R==-1)
			return true;
		else
			return false;
	}

	int maxDepth(struct TreeNode *root)//以root为根的树的深度
	{
    	if(root == NULL)
			return 0;
		else
		{
			int l = maxDepth(root->left);
			int r = maxDepth(root->right);
			return (l > r ? l : r) + 1;
		}
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值