求二叉树深度:
递归的方法:从根节点按照先序顺序遍历二叉树,返回左子树和右子树中较大的深度,再加上1就是根节点的深度。
C++代码实现:
typedef struct TreeNode{
int data;
struct TreeNode* leftchild;
struct TreeNode* rightchild;
}TreeNode, *Bitree;
int TreeMaxDepth(Bitree pRoot){
if(pRoot == NULL){
return 0;
}
int left = TreeMaxDepth(pRoot->leftchild);
int right = TreeMaxDepth(pRoot->rightchild);
return left > right ? left+1 : right+1;
}
二叉树的宽度:
求解二叉树的宽度利用二叉树的层序遍历的思想,把每层的节点保存在队列中,用curwidth记录当前层的宽度,nextwidth记录下一层的宽度。每次把当前层的节点出队,curwidth–,其子节点入队,nextwidth++, 用width来保存最大的宽度。
C++代码如下:
typedef struct TreeNode{
int data;
struct TreeNode* leftchild;
struct TreeNode* rightchild;
}TreeNode, *Bitree;
int WidthOfBiTree(Bitree pRoot){
if(pRoot == NULL){
return 0;
}
int curWidth = 1;
int nextWidth = 0;
int width = 1;
queue<Bitree> node;
node.push(pRoot);
while(!node.empty()){
while(curWidth!=0){
Bitree tmp = node.front();
node.pop();
if(tmp->leftchild != NULL){
nextWidth++;
}
if(tmp->rightchild != NULL){
nextWidth++;
}
curWidth--;
}
if(nextWidth>width){
width = nextWidth;
}
curWidth = nextWidth;
nextWidth = 0;
}
return width;
}
判断是否是平衡二叉树:
平衡二叉树:每个节点的左右子树的深度差不超过1。利用求二叉树深度算法,判断每个节点的左右子树是否满足平衡二叉树的条件即可。
算法一: C++代码实现
bool IsBalance(Bitree pRoot){
if(pRoot == NULL){
return true;
}
int left = TreeMaxDepth(pRoot->leftchild);
int right = TreeMaxDepth(pRoot->rightchild);
int diff = left - right;
if(diff < -1 || diff > 1){
return false;
}
return IsBalance(pRoot->leftchild) && IsBalance(pRoot->rightchild);
}
但是上诉算法不够高效,会重复遍历遍历节点。根据二叉树的后序遍历的思想,我们可以设计出更高效的算法,每遍历到一个节点就记录下当前节点的深度,这样就不需要重复遍历了,只需要线性时间即可判断左右子树的深度是否满足平衡二叉树的条件。
算法二:C++代码实现:
bool IsBalance_fast(Bitree pRoot, int& pDepth){
if(pRoot == NULL){
pDepth = 0;
return true;
}
int left, right;
if(IsBalance_fast(pRoot->leftchild, left) && IsBalance_fast(pRoot->rightchild, right)){
int diff = left - right;
if(diff >= -1 && diff <=1){
pDepth = left > right ? left + 1 : right + 1;
return true;
}
}
return false;
}