题目
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
分析
二叉排序树的定义就是左右子树的高度之差不超过1,且左右子树也是平衡二叉树。因此最简单的思路如下:
- 输入的树为空,直接返回true;
- 否则,判断左右子树高度之差是否不超过1,若不超过1 ,那么递归判断左右子树的是否为平衡二叉树,若是则返回true,若不是则返回false。
但是可以发现这种思路需要大量重复遍历树的结点,算法不够高效。
那么比较高效的算法是在后序遍历的基础上进行判断是否为平衡二叉树。具体思路如下:
- 若树为空,树的高度置为0,直接返回true;
- 在遍历根节点之前递归判断左右子树是否为平衡二叉树,若是计算左右子树高度的之差,若该差值不超过1,则输入的高度为该差值加1,直接返回true;
- 左右子树其中之一不为平衡二叉树直接返回false;
github链接:JZ39-平衡二叉树
C++ 代码
1 递归判断左右子树高度思路
#include <iostream>
#include <cmath>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == NULL){
return true;
}
return this->check_Height(pRoot);
}
bool check_Height(TreeNode* pRoot){
if(pRoot == NULL){
return true;
}
int left = this->TreeDepth(pRoot->left);
int right = this->TreeDepth(pRoot->right);
bool flag;
if(abs(left-right) <= 1){
return this->IsBalanced_Solution(pRoot->left) && this->IsBalanced_Solution(pRoot->right);
}else{
return false;
}
}
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL){
return 0;
}
int left = this->TreeDepth(pRoot->left);
int right = this->TreeDepth(pRoot->right);
return (left>right)?left+1:right+1;
}
};
TreeNode* Create_BinaryTree()
{
TreeNode* T = new TreeNode(0);
char ch;
cin>>ch;
if(ch == '#'){ //“#”是结束标志
T = NULL;
}else{
T->val = int(ch); //对当前结点初始化
T->left = Create_BinaryTree(); //递归构造左子树
T->right = Create_BinaryTree(); //递归构造右子树
}
return T;
}
int main()
{
while(true){
TreeNode* root = Create_BinaryTree();
Solution s;
cout<<s.IsBalanced_Solution(root);
}
return 0;
}
2 后序遍历思路
#include <iostream>
#include <cmath>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return this->IsBalanced(pRoot,&depth);
}
bool IsBalanced(TreeNode* pRoot,int* depth) {
if(pRoot == NULL){
*depth = 0;
return true;
}
int left_depth = 0,right_depth = 0;
if(this->IsBalanced(pRoot->left,&left_depth) && this->IsBalanced(pRoot->right,&right_depth)){
int diff = abs(left_depth-right_depth);
if(diff <= 1){
*depth = 1 + max(left_depth,right_depth);
return true;
}
}
return false;
}
};
TreeNode* Create_BinaryTree()
{
TreeNode* T = new TreeNode(0);
char ch;
cin>>ch;
if(ch == '#'){ //“#”是结束标志
T = NULL;
}else{
T->val = int(ch); //对当前结点初始化
T->left = Create_BinaryTree(); //递归构造左子树
T->right = Create_BinaryTree(); //递归构造右子树
}
return T;
}
int main()
{
while(true){
TreeNode* root = Create_BinaryTree();
Solution s;
cout<<s.IsBalanced_Solution(root);
}
return 0;
}