一、问题描述
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
二、解题思路
思路一:先递归求各结点的深度,根据深度做差值,根据差值判断是否为平衡二叉树
思路二:后序遍历二叉树,在遍历的同时记录深度---避免思路一的重复计算
三、解题算法
1、思路1:根据深度求差值
/******************************
author:tmw
date:2018-8-6
******************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct BiTreeNode
{
int data;
struct BiTreeNode* lchild;
struct BiTreeNode* rchild;
}BiTreeNode;
/**递归求二叉树的深度**/
int TreeDepth( BiTreeNode* root )
{
//递归收敛条件--初始条件
if( root == NULL ) return 0;
int left = TreeDepth(root->lchild);
int right = TreeDepth(root->rchild);
return left>right?left+1:right+1;
}
/**判断二叉树是否为平衡二叉树**/
bool isBalanceTree( BiTreeNode* root )
{
//递归收敛条件--初始条件
if( root == NULL ) return true;
//分别求左右子树的深度
int left_depth = TreeDepth(root->lchild);
int right_depth = TreeDepth(root->rchild);
//计算左右深度差值
int diff = left - right;
if( diff > 1 || diff < -1 )
return false;
return isBalanceTree(root->lchild) && isBalanceTree(root->rchild);
}
2、思路2:后序遍历,同时记录深度
/**思路二:后序遍历二叉树,在遍历的同时记录深度**/
bool isBalanceTreeMethod2( BiTreeNode* root, int* depth )
{
if( root == NULL )
return true;
int left, right;
if( isBalanceTreeMethod2(root->lchild, &left) && isBalanceTreeMethod2(root->rchild, &right) )
{
int diff = left - right;
if( diff <= 1 && diff >= -1 )
{
*depth = left > right ? 1+left : 1+right;
return true;
}
}
return false;
}
梦想还是要有的,万一实现了呢~~~~~ヾ(◍°∇°◍)ノ゙~~~~~~~~