1 解题思想
题目意思是给定一颗树,判断是否高度平衡,即左右子树的高度差不超过1
采用先序的方式递归遍历到最底层,从最底层开始检查高度是否满足条件,左右的高度是否差值超过1,要是超过了就直接return了。
2 原题
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.
3 AC解
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
/** * 递归判断每一颗子树是否满足,并把自己的高度返回 * 每棵树平衡的定义是,左子树的高度和又子数的高度相差不超过1 * * 只要任何一个地方不满足了,就要break * */
public class Solution {
boolean isBalanced = true;
public int dfs(TreeNode root){
if(isBalanced==false)
return -1;
if(root==null) return 0;
int left=dfs(root.left);
int right=dfs(root.right);
if(Math.abs(left-right)>1)
isBalanced=false;
return Math.max(left,right)+1;
}
public boolean isBalanced(TreeNode root) {
dfs(root);
return isBalanced;
}
}