leetcode:110 Balanced Binary Tree-每日编程第十九题
2015-12-11 10:46
507 查看
Balanced Binary Tree
Total
Accepted: 85721 Total
Submissions: 261445 Difficulty: Easy
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).判断root是否平衡(即左右子树的高是否相差在1 内),平衡转2).,如果不平衡,则返回false;
2).判断root的左子树是否平衡,root的右子树是否平衡,即把root的左右节点当成root并重复1).
3).直到NULL结束。
Total
Accepted: 85721 Total
Submissions: 261445 Difficulty: Easy
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).判断root是否平衡(即左右子树的高是否相差在1 内),平衡转2).,如果不平衡,则返回false;
2).判断root的左子树是否平衡,root的右子树是否平衡,即把root的左右节点当成root并重复1).
3).直到NULL结束。
/** * 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 getHeight(TreeNode* root){ if(root==NULL){ return 0; }else{ return max(getHeight(root->left),getHeight(root->right))+1; } } bool isBalanced(TreeNode* root) { if(root==NULL){ return true; } int m = getHeight(root->left); int n = getHeight(root->right); if(abs(n-m)<=1){ return isBalanced(root->left)&&isBalanced(root->right); }else{ return false; } } };
相关文章推荐
- 深刻理解Python中的元类(metaclass)(转)
- 【Google 年度顶级论文】机器学习系统,隐藏多少技术债?
- 1-1.java基础总结
- C++学习
- github桌面软件使用教程
- python --序列的方法
- Struts2 - 常用的constant总结
- java 判断当前操作系统 及获取相关属性
- 【已解决】python ImportError: No module named XXX
- Java之lambda表达式
- mangodb索引问题
- spring mvc 返回json试图如何过滤
- 有序Dict类型(python)
- zend framework 分页 Zend_Paginator 分页搜索条件
- 夺命雷公狗---PHP---玩转安卓1之数据传递
- JAVA性能优化的五种方式
- 12.ftp的vsftpd服务安装
- leetcode:231 Power of Two-每日编程第十八题
- c# timer使用
- Python性能优化