剑指offer : 平衡二叉树

题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树,且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

class Solution {
public:
	int TreeDepth(TreeNode* pRoot)
	{
		if (pRoot == nullptr)
			return 0;
		int left = TreeDepth(pRoot->left);
		int right = TreeDepth(pRoot->right);
		int _TreeDepth = max(left, right) + 1;
		return _TreeDepth;
	}
public:
	bool IsBalanced_Solution(TreeNode* pRoot)
	{
		if (pRoot == nullptr)
			return true;
		int left = TreeDepth(pRoot->left);
		int right = TreeDepth(pRoot->right);
		int diff = left - right;
		if (diff > 1 || diff < -1)
			return false;
		return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);


	}
};

猜你喜欢

转载自blog.csdn.net/Shile975/article/details/89283853