leetcode 110-判断一棵树是否为平衡二叉树

xiaoxiao2021-02-28  117

平衡二叉树的定义: 空树或者左右子树的高度差不超过1且左右子树也是平衡二叉树。

需要用到计算深度的方法:

public int depth(TreeNode root) { if (root == null) return 0; int left = depth(root.left); //计算左子树的深度 int right = depth(root.right); //计算右子树的深度 return Math.max(left, right) + 1; //返回较大值 }

根据平衡二叉树的定义写代码:

public boolean isBalanced(TreeNode root) { if (root == null) return true; //空树是平衡二叉树 if (Math.abs(depth(root.left) - depth(root.right)) > 1) return false; //左右子树高度差大于1,不是平衡二叉树 else return isBalanced(root.left) && isBalanced(root.right); // 递归判断左右子树是否为平衡二叉树 }
转载请注明原文地址: https://www.6miu.com/read-50826.html

最新回复(0)