[leetcode]Balanced Binary Tree
2015-11-25 09:41
316 查看
题目描述如下:
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,并且左右两个子树都是一棵平衡二叉树。
两个递归函数,一个判断当前结点左右子树的高度差,另一个求当前结点的子树高度,代码如下:
感觉通过一段时间在leetcode上的练习写递归时的思路越来越清晰了,代码也比当初简洁了不少。
题目链接:https://leetcode.com/problems/balanced-binary-tree/
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,并且左右两个子树都是一棵平衡二叉树。
两个递归函数,一个判断当前结点左右子树的高度差,另一个求当前结点的子树高度,代码如下:
public class Solution { public boolean isBalanced(TreeNode root) { if(root == null) return true; System.out.println("LeftHeight:" + getHeight(root)); if(Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1) return isBalanced(root.left) && isBalanced(root.right); return false; } public int getHeight(TreeNode root){ if(root == null) return 0; return Math.max(getHeight(root.left), getHeight(root.right)) + 1; } }
感觉通过一段时间在leetcode上的练习写递归时的思路越来越清晰了,代码也比当初简洁了不少。
题目链接:https://leetcode.com/problems/balanced-binary-tree/
相关文章推荐
- java判断字符串是否为空的常用方法
- 【论文阅读】Retrieving Similar Similar Styles to Parse Clothing(相关工作)
- HTTPS背后的加密算法
- 拉格朗日对偶性和似然函数
- Android 如何在Eclipse中查看Android API源码以及support包源码(转载)
- UVA 116——Unidirectional TSP
- 触发器--控制主键自增长度
- 如何生成一维码
- spring配置文件的加载
- Java 中无参带返回值方法的使用
- 我的代码风格规范(动态更新)
- [Built-in Functions] - H
- 重建二叉树
- angularJS学习之路(三十)---自定义指令---templateUrl
- strcpy和memcpy的区别
- iOS-即时通讯-环信
- larave5.1l队列
- 中耳炎
- Altium Designer(Protel)网络连接方式Port和Net Label详解
- B样条曲线