//Implement a function to check if a tree is balanced. For the purposes of this question,
//a balanced tree is defined to be a tree such that no two leaf nodes differ in distance
//from the root by more than one.
#include <iostream>
#include <math.h>
using namespace std;
int maxDepth(TreeNode * node)
{
if (node == NULL)
return 0;
return 1 + max(maxDepth(node->left), maxDepth(node->right));
}
int minDepth(TreeNode * node)
{
if (node == NULL)
return 0;
return 1 + min(minDepth(node->left), minDepth(node->right));
}
bool isBalanced(TreeNode * node)
{
int differ = abs(maxDepth(node), minDepth(node));
if (differ > 1)
return false;
else
return true;
}
crack the code interview 4.1
最新推荐文章于 2020-08-13 08:40:42 发布
本文介绍了一个用于检查二叉树是否平衡的功能实现。平衡树被定义为任意两个叶子节点到根的距离不超过一的二叉树。文中提供了计算最大深度和最小深度的方法,并通过两者的差值判断树是否平衡。
1万+

被折叠的 条评论
为什么被折叠?



