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.
测试平衡二叉树是一个相当古老的问题了,调用递归分分钟解决,但是万万没想到,我居然犯了一个小小的错误,到时候time limited 上代码,大家可以参考一下,由于只提供一个isBalance函数,且返回的是bool值,所以我们需要另外一个函数来计算层高,如下:
/** * 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* root) { int theheight=0; if(root == NULL) { return 0; } else { theheight=height(root->left)>height(root->right)?height(root->left)+1:height(root->right)+1; return theheight; } }
int height(TreeNode* root) { int theheight=0; if(root == NULL) { return 0; } else { int l=height(root->left); int r=height(root->right); theheight=l>r?l+1:r+1; return theheight; } }接着使用isBalance 进行一下判断:
bool isBalanced(TreeNode* root) { int leftheight,rightheight; if(root == NULL ) { return true; } leftheight=root->left!=NULL?height(root->left)+1:0; rightheight=root->right!=NULL?height(root->right)+1:0; if((leftheight-rightheight)<=1 && isBalanced(root->left) && isBalanced(root->right) ) { return true; } else { return false; } }accept后发现时间还是有点长,于是想到height函数在计算层高的时候就可以顺便把子树的balance状态统计了,于是。。。。
class Solution { public: bool isBalanced(TreeNode* root) { int n=height(root); if(n<0) { return false; } else{ return true; } } public: int height(TreeNode* root) { int theheight=0; if(root == NULL) { return 0; } else { int r=height(root->right); int l=height(root->left); if(abs(r-l)<=1 && r!=-1 && l!=-1 ) { theheight=r>l?r+1:l+1; return theheight; } else{ return -1; } } } };但是此时啊,又出现了一个问题,我发现时间并没有提高很多,分明减少了一个递归,为何时间竟然不减少,眼尖的你们早就发现了 对不对,我多写了一个public,就是这个小小的public呀 在去掉之后,时间由原来的16ms变为12ms,飞跃啊,