[leetcode]Balanced Binary Tree
来源:互联网 发布:中国数据南京 编辑:程序博客网 时间:2024/06/16 00:40
题目描述如下:
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/
0 0
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode-Balanced Binary Tree
- LeetCode - Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- LeetCode | Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- UIBarButtonItem (系统 Item 样式)
- 显示器 如何切换输入源
- Linux操作EFI固件的环境变量
- 医学常识
- Mac操作知识积累(不断补充更新)
- [leetcode]Balanced Binary Tree
- MYSQL中'TYPE=MyISAM'错误的解决方案
- [ecshop 资料] ecshop 购物车显示积分
- 联合体union的使用
- Android studio 2.0 预览版发布
- 29.c/c++程序员面试宝典-类型转换构造函数
- Ubuntu-gcc版本切换
- jquery与后台进行数据交互--前台发单一数据对象,后台返回一个json字符串 jsp页面
- 20个实用便捷的CSS3工具、库及实例