[LeetCode] 110. Balanced Binary Tree Java
题目:
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.
题意及分析:给出一课二叉树,判断是否是二叉平衡树。使用递归,分别求出左右子树的高度,然后相减,看是否符合条件,若符合,则分别判断左右子节点是否符合。
代码:
/** * 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) { if(root==null) return true; int left = count(root.left); int right =count(root.right); return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right); } public int count(TreeNode node){ //求一棵树的高度,为左右子树的最大高度+1 if(node==null) return 0; return Math.max(count(node.left),count(node.right))+1; } }