这个题目纠结了一会儿,终于从二叉树转化到AVL了。题目如下:
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.
给一个二叉树判断它是不是平衡二叉树,根据平衡二叉树的定义:左右子树高度差的绝对值要小于1.那么我们在判断的时候就是拿到一个节点然后计算它两边左右子树的最大高度,判断这两者差的绝对值是否大于1就行。这样的话就得先拿递归写个判断树最大高度的函数,然后在判断函数里面调用就可以了。题解如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int MaxDepth(TreeNode *temp)
{
if (temp == NULL)
return 0;
else
{
int aspros = MaxDepth(temp->left);
int defteros = MaxDepth(temp->right);
return 1 + (aspros>defteros ? aspros : defteros);
}
}
bool isBalanced(TreeNode *root)
{
if (root == NULL)
{
return true;
}
int aspros = MaxDepth(root->left);
int defteros = MaxDepth(root->right);
if (abs(aspros - defteros)>1)
return false;
// This way is wrong!
//if (abs(DepthTree(temp->left) - DepthTree(temp->right) > 1))
// return false;
else
return (isBalanced(root->left) && isBalanced(root->right));
}
};
这次学会了在递归中使用返回值。