输入一棵二叉树,判断该二叉树是否是平衡二叉树。

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<list>
#include<iterator>
#include<queue>
#include<stack>
#include<algorithm>
#include<forward_list>
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; //如果树为空,返回false
		if (pRoot->right == NULL && pRoot->left == NULL) return true;//如果左右字数都等于空时返回true
		if (pRoot->right != NULL && pRoot->left == NULL)//当左子树为空,右子树不为空时
		{
			if (Depth(pRoot->right) > 1) return false;
			else  return true;
		}
		if (pRoot->right == NULL && pRoot->left != NULL)//当右子树为空,左子树不为空时
		{
			if (Depth(pRoot->left) > 1) return false;
			else  return true;
		}

		//处理都不为空的情况
		if (abs(Depth(pRoot->right) - Depth(pRoot->left)) > 1) //如果二叉树的左子树和右字数的深度相差大于1,返回false
			return false;
		else
			return IsBalanced_Solution(pRoot->right)&&IsBalanced_Solution(pRoot->left);

		
	}

	int Depth(TreeNode *T)//获取二叉树的深度
	{
		if (T == NULL) return 0;
		int m = Depth(T->left);
		int n = Depth(T->right);
		if (m > n) return m + 1;
		else return n + 1;
		
	}

	void InOrderTraversData(TreeNode* T) //中序遍历得到T的值
	{
		if (T == NULL) return;
		else
		{
			InOrderTraversData(T->left);
			cout << T->val << "  ";
			
			InOrderTraversData(T->right);
		}
	}

	void preCreate(TreeNode* &T)  //前序创建
	{
		int num;
		cin >> num;
		if (num == 0) return;
		else
		{
			T = new TreeNode(num);
			preCreate(T->left);
			preCreate(T->right);
		}
	}
};

int main()
{

	Solution so;
	TreeNode *T=NULL;
	TreeNode *copy = NULL;

	so.preCreate(T);
	cout << "创建二叉树成功!"<<endl;
	//cout << "二叉树的深度是:" << endl;
	//cout << so.Depth(T)<<endl;

	cout << "输入的二叉树是否是平衡二叉树:" << endl;
	cout << so.IsBalanced_Solution(T) << endl;

	

	cout << endl;
	return 0;
}
原文地址:https://www.cnblogs.com/wdan2016/p/6007230.html