5.1.10—二叉树的遍历—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.

#include "BinaryTree.h"
#include <stack>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
//===判断一棵二叉树是否是平衡树----递归版本
int HeightTree(BinaryTreeNode *proot)
{
	if (!proot) return 0;
	else
		return HeightTree(proot->m_pLeft) > HeightTree(proot->m_pRight) ? 1 + HeightTree(proot->m_pLeft) : HeightTree(proot->m_pRight) + 1;
}
bool IsBalancedTree(BinaryTreeNode *proot)
{
	if (!proot)
		return true;
	
	int left = HeightTree(proot->m_pLeft);
	int right = HeightTree(proot->m_pRight);
	if (abs(left - right) > 1)return false;
	return IsBalancedTree(proot->m_pLeft)&&IsBalancedTree(proot->m_pRight);

}
// ====================测试代码====================
//            8
//        6      10
//       5 7    9  11
int main()
{
	//===
	BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
	BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
	BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
	BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
	BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);

	ConnectTreeNodes(pNode8, pNode6,pNode10);
	ConnectTreeNodes(pNode6, pNode5, pNode7);
	ConnectTreeNodes(pNode10, pNode9, pNode11);
	
	//===
	//PrintTree(pNode8);
	//===
	bool flag = IsBalancedTree(pNode8);
	cout << flag << endl;


	DestroyTree(pNode8);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值