题目链接

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=0&tqId=0&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题意

判断一棵树是否为平衡二叉树

思路

法一,定义版:按定义,自上而下遍历树,会有重复计算。

法二,优化版:自下而上遍历树,若不平衡则返回-1,至多遍历树一遍。

相关知识

平衡二叉树:或空树,或根结点左右子树高度差<=1,且左右子树也为平衡二叉树。

代码

定义版

class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==NULL){return true;}
else if(abs(getDepth(pRoot->left)-getDepth(pRoot->right))<=1){
return true;
}
return false;
}
private:
int getDepth(TreeNode* pRoot){
if(pRoot==NULL){return true;}
else return max(getDepth(pRoot->left),getDepth(pRoot->right))+1;
}
};

优化版

class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
return getDepth(pRoot)!=-1;
}
private:
int getDepth(TreeNode* pRoot){
if(pRoot==NULL){return 0;}
else{
int left=getDepth(pRoot->left);
if(left==-1){return -1;} int right=getDepth(pRoot->right);
if(right==-1){return -1;} if(abs(right-left)>1){return -1;}
else{return max(left,right)+1;}
}
}
};

最新文章

  1. spring 定时任务配置
  2. 【大数据技巧】日均2TB日志数据在线快速处理之法
  3. ajax 参数有中文
  4. 重拾java系列一java基础(1)
  5. Java文件读写
  6. 深入分析Java的序列化与反序列化
  7. SharePoint 2010 升级到2013时间 为了确保用户可以连接,但无法改变升级数据
  8. DOS批处理的字符串功能
  9. 手机自动化测试:appium源码分析之bootstrap十二
  10. MySQL监听数据库存储过程出现异常
  11. 理解Python中的yield
  12. 简易promise的实现(二)
  13. 隔离 docker 容器中的用户
  14. pycharm的快捷键
  15. insmod 签名问题
  16. free(): invalid next size (fast): 0x000000xxx
  17. nasm学习资料
  18. gdb调试多进程多线程程序
  19. db2 backup export
  20. Centos7下python3安装pip-9.0.1

热门文章

  1. 微信小程序插件 - 开发教程
  2. strcore.cpp(156) 内存泄漏
  3. netty为啥要二次开发
  4. JSON数据的解析和生成(Swift)
  5. Eclipse编译Android项目时出现的问题:Android requires compiler compliance level 5.0 or 6.0. Found &#39;1.8&#39; instead.
  6. Hibernate学习笔记1.1(简单插入数据)
  7. C#图像处理:截图程序(包含鼠标)
  8. FMS Dev Guide学习笔记(权限控制)
  9. swift视图的添加及层次变动和基本动画
  10. 吴裕雄 28-MySQL 序列使用