LeetCode Balanced Binary Tree
2015-09-05 00:44
267 查看
原题链接在这里:https://leetcode.com/problems/balanced-binary-tree/
用递归方法求最大深度,如果左右最大深度相差大于一,则返回-1,若是已有左或者右的返回值为-1,则立即返回-1.
最后看返回到root时是否为一个负数,若是负数则不是balanced,若是正数,则返回了最大深度,是balanced.
最大深度可参见Maximum
Depth of Binary Tree.
AC Java:
用递归方法求最大深度,如果左右最大深度相差大于一,则返回-1,若是已有左或者右的返回值为-1,则立即返回-1.
最后看返回到root时是否为一个负数,若是负数则不是balanced,若是正数,则返回了最大深度,是balanced.
最大深度可参见Maximum
Depth of Binary Tree.
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { return maxDepth(root) >= 0; } private int maxDepth(TreeNode root){ if(root == null){ return 0; } int left = maxDepth(root.left); int right = maxDepth(root.right); if(left < 0 || right < 0 || Math.abs(left - right) > 1){ return -1; } return Math.max(left,right)+1; } }
相关文章推荐
- 大二任务
- 约瑟夫环问题求解
- LeetCode Balanced Binary Tree
- 第0课第3节 刚接触开发板之重烧整个系统
- 笔试题:求数组中和为sum的乘积最小的一对组合
- 剑指offer:树的子结构 代码实现
- Matlab图形绘制经典案例 (2)
- 万能的BaseDAO和注解的应用
- LeetCode201——Bitwise AND of Numbers Range
- Matlab图形绘制经典案例 (1)
- XHR——XMLHttpRequest对象
- 关于PHP程序员解决问题的能力
- wamp25 让局域网可以访问pma
- lvs学习笔记
- POJ 3352 双连通缩点以及求桥和边双连通分量
- HttpServletRequestAnd HttpServletResponse
- yum错误
- [python]学渣的心酸(求职篇)
- 网络整合营销概念2015
- 网络整合营销概念2015