题解 | #平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
速度还是挺快的,就是占用内存好像有些拉胯。
运行时间:13ms
超过64.47% 用Java提交的代码
占用内存:11676KB
超过0.59%用Java提交的代码
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if (root == null) { // 如果为空,返回true,因为空树为平衡二叉树 return true; } int l = depth(root.left); // 计算左子树长度 int r = depth(root.right); // 计算右子树长度 if (Math.abs(r - l) > 1) { //如果左右子树长度差大于一,必不可能为平衡二叉树 return false; } else { // 只有当前根节点为平衡二叉树并且左右子树都为平衡二叉树时,才判定为平衡二叉树 return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right); } } // 计算树的长度 public static int depth(TreeNode root) { if (root == null) { return 0; } return 1 + Math.max(depth(root.left), depth(root.right)); } }