解题思路:先求出根节点的左右节点深度,当深度差值大于1时,输出false;否则输出true。注意当根节点为空时,也是平衡二叉树。
import java.util.*;
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root!=null){
if(Math.abs(depth(root.left)-depth(root.right))<2){
return true;
}
else{
return false;
}
}
return true;
}
public int depth(TreeNode root){
if(root==null){
return 0;
}
int l=depth(root.left);
int r=depth(root.right);
if(l<r){
return r+1;
}
else{
return l+1;
}
}
}
京公网安备 11010502036488号