【LeetCode】Balanced Binary Tree
来源:互联网 发布:金山软件管家office 编辑:程序博客网 时间:2024/04/28 13:18
题目
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,若大于则返回false,否则递归调用判断左右子树是否同时满足平衡的条件。代码如下:
public class Solution { public boolean isBalanced(TreeNode root) { if(root==null){ return true; } // 如果左子树和右子树高度相差大于1,则非平衡二叉树 if(Math.abs(getDepthRec(root.left)-getDepthRec(root.right))>1){ return false; } // 递归判断左子树和右子树是否为平衡二叉树 return isBalanced(root.left)&&isBalanced(root.right); } //a.若二叉树为空,深度为0;b.若二叉树不为空,深度=max(左子树深度,右子树深度)+1 private int getDepthRec(TreeNode root){ if(root==null){ return 0; } int leftDepth=getDepthRec(root.left); int rightDepth=getDepthRec(root.right); return Math.max(leftDepth,rightDepth)+1; }}
---EOF---
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
- 腾讯第三方登陆的SDKarm64不支持
- VS2013快捷键及技巧
- extern "C"的用法解析
- Android Studio使用教程(二)
- 分享键盘按键对应的ASCII码值
- 【LeetCode】Balanced Binary Tree
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推
- 构建者(builder) in Java
- web开发如何屏蔽浏览器输入框下拉历史的输入记录
- 关于MFC项目中使用WebBrowser控件禁止脚本错误的方法
- 关于"从不是创建控件的线程访问它”
- 中介者(mediator) in Java
- 铜仁
- windows 下 protobuf 使用