[Cracking the Coding Interview] 4.4 Check Balanced
Implement a function to check if a binary tree is balanced. For the purpose of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
这道题让我们检查一棵树是不是平衡的,根据题目平衡二叉树的定义我们可以对于每个node递归的检测一下它的substrees是否符合这个条件。见如下的代码:
height函数递归的计算出一棵树的高度,is_balanced?函数递归的判断每个node的子树是不是平衡。
class TreeNodeattr_accessor :val, :left, :rightdef initialize(val)@val = val@left = nil@right = nilend enddef is_balanced?(root)return true if root.nil?if (height(root.left) - height(root.right)).abs <= 1return is_balanced?(root.left) && is_balanced?(root.right)elsereturn falseend enddef height(root)return 0 if root.nil?left_height = height(root.left)right_height = height(root.right)return [left_height, right_height].max + 1 end
转载于:https://www.cnblogs.com/infinitycoder/p/9189513.html
[Cracking the Coding Interview] 4.4 Check Balanced相关推荐
- Cracking the coding interview
转自:http://hawstein.com/posts/ctci-solutions-contents.html Cracking the coding interview--问题与解答 March ...
- 经典算法题目:Cracking the coding interview 问题与解答
Cracking the coding interview--问题与解答 March 14, 2013 作者:Hawstein 出处: http://hawstein.com/posts/ctci-s ...
- [Free] Cracking the Coding Interview 6th Download
[Free] Cracking the Coding Interview 6th Download 推荐给有梯子的童鞋们! https://www.pdfdrive.com/cracking-the- ...
- 渣基础:比照Hawstein学Cracking the coding interview(1)
<C++ Primer 第五版>书实在是太长,太厚了.总是看了十几页就看累了,坚持不了多久,想了想还是别勉强自己,决定把它当工具书查看,或者积累足够的C++经验后再翻阅一遍. 目前的打算是 ...
- 《Cracking the Coding Interview》——第18章:难题——题目11
2014-04-29 04:30 题目:给定一个由'0'或者'1'构成的二维数组,找出一个四条边全部由'1'构成的正方形(矩形中间可以有'0'),使得矩形面积最大. 解法:用动态规划思想,记录二维数组 ...
- 《Cracking the Coding Interview》——第6章:智力题——题目5
2014-03-20 01:08 题目:扔鸡蛋问题.有一个鸡蛋,如果从N楼扔下去恰好会摔碎,低于N楼则不碎,可以继续扔.给你两个这样的鸡蛋,要求你一定得求出N,怎么扔才能减少最坏情况下的扔的次数? 解 ...
- 《Cracking the Coding Interview》——第18章:难题——题目3
2014-04-29 01:02 题目:从m个整数里随机选出n个整数,要求等概率. 解法:和洗牌的算法类似,每次随机抽出一个数,抽n次即可.时间复杂度O(m * n),空间复杂度O(m). 代码: 1 ...
- 《Cracking the Coding Interview》——第16章:线程与锁——题目3
2014-04-27 19:26 题目:哲学家吃饭问题,死锁问题经典模型(专门用来黑哲学家的?). 解法:死锁四条件:1. 资源互斥.2. 请求保持.3. 非抢占.4. 循环等待.所以,某砖家拿起一只 ...
- Cracking The Coding Interview 9.1
//原文: // // You are given two sorted arrays, A and B, and A has a large enough buffer at the end to ...
最新文章
- gff3转mysql_五月 | 2013 | 陈连福的生信博客
- 深度学习在机器人视觉中的局限与优势(综述)
- 漏答题、偏科、多次复读,30 位互联网大佬考上啥大学了?
- SAP UI5 应用开发教程之六十四 - 基于 OData V4 的 SAP UI5 表格控件如何实现 filter(过滤) 和 sort(排序)功能试读版
- SQLServer常用的配置函数笔记
- 解答网友提问 | 使用VS2022快速生成React/Angular/Vue.js + Web API前后端集成项目
- Spring RESTful Web服务中的异常处理
- Bzoj2694/Bzoj4659:莫比乌斯反演
- python遍历文件夹下所有文件名中含有指定_Python 遍历目录找出包含指定字符串的文件夹...
- 二叉树——求先序排列(洛谷 P1030)
- 2——类和对象的关系
- 【C语言】c语言基础知识梳理(超全)
- 单片机c语言开关,10手把手教你学单片机的C语言程序设计_开关语句和循环语句.pdf...
- ElasticHD Windows环境下安装
- Bootstrap实战 - 评论列表
- zookeeper启动报错: Invalid configuration, only one server specified (ignoring)
- 假AI?如何辨识 AI 界的snake oil
- Liunx 创建隐藏文件夹
- VLAN间如何实现互连?干货奉上!!!
- 基于FPGA的自动小车控制设计Verilog开发