重归刷题之路
leetcode吧
全部回复
仅看楼主
level 1
justopit2 楼主
数学建模三天把我身体掏空了一大半。还是刷题好啊。今天先刷一道简单的,养养气势。
2017年09月18日 15点09分 1
level 1
justopit2 楼主
110. 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.
就是按照定义来,有点优化在实现上
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int height( TreeNode * ptr )
{
if( !ptr )
{
return 0;
}
int a = height( ptr->left );
if( a == -1 )
{
return a;
}
int b = height( ptr->right );
if( b == -1 )
{
return b;
}
if( abs( a- b ) > 1 )
{
return -1;
}
return max( a, b ) + 1;
}
bool isBalanced(TreeNode* root) {
return height( root ) != -1;
}
};
2017年09月18日 16点09分 2
1