[leetcode] 110. Balanced Binary Tree 解题报告
2015-12-24 17:38
429 查看
题目链接:https://leetcode.com/problems/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.
思路:求解一个树是否平衡可以转化为求二叉树的深度,一旦发现左右子树深度相差超过1,则说明不是平衡树。
代码如下:
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.
思路:求解一个树是否平衡可以转化为求二叉树的深度,一旦发现左右子树深度相差超过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 getDepth(TreeNode* root, bool& flag) { //如果当前节点为空则返回深度0,如果flag为false,说明已经判断这不是平衡树,结束程序 if(!root || !flag) return 0; int dp1 = getDepth(root->left, flag); int dp2 = getDepth(root->right, flag); if(abs(dp1 - dp2) > 1) //如果左右子树深度差大于1,说明不是平衡树 flag = false; return max(dp1, dp2) + 1; } bool isBalanced(TreeNode* root) { if(root == NULL) return true; bool flag = true; getDepth(root, flag); return flag; } };
相关文章推荐
- Java 8十个lambda表达式案例
- OC学习篇之-----KVC
- Swift主题色顶级解决方案
- [css]我要用css画幅画(七) - 哆啦A梦
- Python的数据类型
- android zxing自定义界面,点击按钮开关闪光灯
- MFC与C#连接MYSQL乱码问题
- Servlet 实现下载功能
- js封装时间转换工具,实现日期之前的转换
- 技术人员如何去面试?
- 接口学习
- test
- C++科学计算库GSL在Windows下的配置
- Perceptron Learning Algorithm(python实现)
- ASP.NET 对象的使用,深化
- JSP转发和重定向的区别
- 翻译:Linux的电源管理架构
- 用原生js实现数据双向绑定
- 解决Android Studio的ADB not responding错误
- 一个设置多个类似标志的好办法 iOS 类似flag