仔细,仔细,仔细!
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int getheight(TreeNode *p)
{
if(!p)
return 0;
else
return 1 + max(getheight(p->left), getheight(p->right));
}
bool isBalanced(TreeNode *root)
{
if(!root)
return true;
q.push(root);
while(!q.empty())
{
TreeNode *p = q.front();
q.pop();
if(abs(getheight(p->left) - getheight(p->right)) > 1)
return false;
else
{
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
}
return true;
}
private:
queue<TreeNode*> q;
};
int main(void)
{
TreeNode *root = new TreeNode(0);
/*
TreeNode *node1 = new TreeNode(1); root->left = node1;
TreeNode *node2 = new TreeNode(2); root->right = node2;
TreeNode *node3 = new TreeNode(3); node1->left = node3;
TreeNode *node4 = new TreeNode(4); node1->left = node4;
TreeNode *node5 = new TreeNode(5); node3->left = node5;
TreeNode *node6 = new TreeNode(6); node4->right = node6;*/
Solution s;
cout << s.isBalanced(root) << endl;
return 0;
}