leetcode第一刷_Balanced Binary Tree

来源:互联网 发布:jquery ajax传递json 编辑:程序博客网 时间:2024/05/20 01:08

二叉平衡树好火啊,几乎每个公司的笔试题里都有它,考了好多次我都不会,挂笔试很有可能就是因为它,还有一个它的同伙叫二叉搜索树,貌似人气比它还要高一些。二叉平衡树是什么样的树呢,是每个节点的左右子树高度相差绝对值都不超过1。好,你说你终于回了,这不很简单吗,求一下根节点的左右字数高度,如果满足,他就是,否则就不是嘛。不是啊亲,要求是所有节点都满足这个条件,判断的时候必须每个节点都验证的!

扯了这么长,其实看看代码就明白了,怎么有种在贴吧发言要凑够15字的感觉。

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. int getHeight(TreeNode *root){  
  2.     if(root == NULL)    return 0;  
  3.     if(!root->left&&!root->right)   return 1;  
  4.     return max(getHeight(root->left), getHeight(root->right))+1;  
  5. }  
  6. class Solution {  
  7. public:  
  8.     bool isBalanced(TreeNode *root) {  
  9.         if(root == NULL)    return true;  
  10.         if(!root->left && !root->right) return true;  
  11.         if(isBalanced(root->left)&&isBalanced(root->right)&&abs(getHeight(root->left)-getHeight(root->right))<=1)  
  12.             return true;  
  13.         return false;  
  14.     }  
  15. };  http://pro851ecb33.isitestar.cn/
    http://pro3e101ba8.isitestar.cn/
0 0
原创粉丝点击