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