110.Balanced Binary Tree

2015-07-20 17:18:12 · 作者: · 浏览: 5

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binarytree in which the depth of the two subtrees of every nodenever differ by more than 1.

HideTags

Tree Depth-first Search

#pragma once
#include
  
   
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

//取最大值
int max(int a, int b)
{
	if (a > b)
		return a;
	return b;
}

//求深度
int findDepth(TreeNode* p)
{
	if (!p)
		return 0;
	return max(findDepth(p->left), findDepth(p->right)) + 1;
}

//平衡条件:左平衡+右平衡+左右深度差小于等于1
bool isBalanced(TreeNode *root) 
{

	if (!root)//空节点也平衡
		return true;
	if (isBalanced(root->left) && isBalanced(root->right) && abs(findDepth(root->left) - findDepth(root->right)) <= 1)
		return true;
	return false;
}

void main()
{
	TreeNode* t1 = new TreeNode(1);
	TreeNode* t12 = new TreeNode(2);
	TreeNode* t22 = new TreeNode(2);
	TreeNode* t13 = new TreeNode(3);
	TreeNode* t23 = new TreeNode(3);
	TreeNode* t14 = new TreeNode(4);
	TreeNode* t24 = new TreeNode(4);

	t1->left = t12;
	t12->left = t13;
	t13->left = t14;
	t1->right = t22;
	t22->right = t23;
	t23->right = t24;

	cout << isBalanced(t1) << endl;
	cout << findDepth(t12) << endl;
	system("pause");
}