leetcode : Balanced Binary Tree
2015-09-01 20:41
375 查看
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.
问题描述:
求解平衡二叉树。
代码实现:
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: bool isBalanced(TreeNode* root) { if(root==NULL) { return true; } int lh=height(root->left); int rh=height(root->right); int dif=lh>rh ? lh-rh : rh-lh; if(dif>1) return false; else { return isBalanced(root->left) && isBalanced(root->right); } } int height(TreeNode* root) { if(root==0) return 0; int lh=height(root->left); int rh=height(root->right); return lh>rh ? lh+1 : rh+1; } };
相关文章推荐
- hdu(5422)——Rikka with Graph
- 汇顶科技(笔试加面试)
- 数据库 Sqlite数据库
- 把一个项目作为library加入其它项目出现莫名错误
- 三种方式上传文件-Java
- Mysql安装、启动与使用
- 判断101~200有多少个素数,并输出这些素数
- 尽量用pass-by-reference-to-const(const引用)替换pass-by-value(传值)
- EditText控件及相关操作
- 尽量用pass-by-reference-to-const(const引用)替换pass-by-value(传值)
- UVA 1149 Bin packing
- ViewPager(页面滑动,加动态点,循环,加标题)
- 编写一个程序找出100~999之间所有的水仙花数
- GCC 编译详解 (转)
- 同时用两个定时器控制蜂鸣器发声,定时器0控制频率,定时器1控制同个频率持续的时间,间隔300ms依次输出1,10,50,100,200,400,800,1K的方波
- 【单链表】
- Android:Layout_weight的深刻理解
- 1094. The Largest Generation (25)
- mongodb创建用户操作
- 面试题24:二叉搜索树的后序遍历序列