Cracking the coding interview--Q4.1
来源:互联网 发布:淘宝客伴侣龙腾管家 编辑:程序博客网 时间:2024/05/22 14:29
题目
原文:
Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
译文:
实现一个函数去检查一个树是否是平衡,对于这个问题的目的,一个平衡的树是被定义为任意两个叶子结点到根结点的距离之差不大于1。
解答
首先要审清楚题目的“平衡”的意思,是指任意两个叶子到根结点距离之差不大于1,所以并不是要判断是否是平衡二叉树(空树或它的左右两个子树的高度差的绝对值不超过1),方法如下:
public static int maxDepth(TreeNode root) {if (root == null) {return 0;}return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));}public static int minDepth(TreeNode root) {if (root == null) {return 0;}return 1 + Math.min(minDepth(root.left), minDepth(root.right));}public static boolean isBalanced(TreeNode root){return (maxDepth(root) - minDepth(root) <= 1);}
---EOF---
0 0
- Cracking the coding interview--Q4.1
- Cracking the coding interview--Q4.1
- Cracking the coding interview--Q4
- Cracking the coding interview--Q4.2
- Cracking the coding interview--Q4.3
- Cracking the coding interview--Q4.4
- Cracking the coding interview--Q4.5
- Cracking the coding interview--Q4.6
- Cracking the coding interview--Q4.7
- Cracking the coding interview--Q4.8
- Cracking the coding interview--Q4.2
- Cracking the coding interview--Q4.3
- Cracking the coding interview--Q4.4
- Cracking the coding interview--Q4.5
- Cracking the coding interview--Q4.6
- Cracking the coding interview--Q4.7
- Cracking the coding interview--Q4.8
- Cracking the Coding Interview
- PHP的CURLOPT_POSTFIELDS参数使用数组和字符串的区别
- Java之命令模式(Command Pattern)
- QC新旧七图汇总连载1——因果图
- POJ 1595 Prime Cuts (ZOJ 1312) 素数打表
- 十三个强大的Linux性能监测工具
- Cracking the coding interview--Q4.1
- 浅谈ThreadLocal
- 游戏程序员的2013年终总结
- Side Project - 愛羽球 v1.2.4 提交了
- merge intervals
- because和because of
- 像素间的基本关系之距离度量
- uva - 10026 - Shoemaker's Problem(贪心)
- linux 下ftp服务的搭建