110. 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.
方法一、递归的方法
(1)从根节点开始得遍历会导致很多节点的多次遍历,代码如下:
int treeDepth(TreeNode* root)
{
if(root == NULL)
return 0;
queue<TreeNode*> que;
que.push(root);
int countLevNodes = 1;
int depth = 0;
while(!que.empty())
{
TreeNode* temp = que.front();
que.pop();
countLevNodes--;
if(temp->left != NULL)
que.push(temp->left);
if(temp->right != NULL)
que.push(temp->right);
if(countLevNodes == 0)
{
depth++;
countLevNodes = que.size();
}
}
return depth;
}
bool isBalanced(TreeNode* root) {
if(NULL == root)
return true;
int left = treeDepth(root->left);
int right = treeDepth(root->right);
int diff = abs(left - right);
if(diff > 1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
(2)从后序开始遍历,使得很多节点的遍历只用遍历一次
采用的后续遍历的方式遍历二叉树的每一个节点的,在遍历到一个节点之前我们就已经遍历了它的左右子树。只要在遍历每个节点的时候记录它的深度(某一节点的深度等于
它到叶结点的路径的长度),我们就可以一边遍历一边判断每个节点是不是平衡的
bool isBalanced(TreeNode* root,int* pdepth)
{
if(NULL == root)
{
*pdepth = 0;
return true;
}
int left,right;
if(isBalanced(root->left,&left)&&isBalanced(root->right,&right))
{
int diff = left - right;
if(abs(diff)<=1)
{
*pdepth = 1 + (left>right?left:right);
return true;
}
}
return false;
}
bool isBalanced(TreeNode* root) {
int depth = 0;
return isBalanced(root,&depth);//由于每一次调用该函数都要去改变depth的数值,所以depth为引用传递
}
方法二、采用dfs的方法来计算每个节点的左右孩子节点的高度
int dfsHeight (TreeNode *root) {
if(NULL == root)
return 0;
int leftHeight = dfsHeight(root->left);
if(leftHeight == -1) return -1;
int rightHeight = dfsHeight(root->right);
if(rightHeight == -1) return -1;
if (abs(leftHeight - rightHeight) > 1) return -1;
return max (leftHeight, rightHeight) + 1;
}
bool isBalanced(TreeNode* root) {
return dfsHeight(root) != -1;
}