题解 | #奶牛的居住区域#

奶牛的居住区域

https://www.nowcoder.com/practice/9265378f210b4ed5939424152f832221

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    public boolean cowLivingArea (TreeNode root) {
        // write code here
      return  isBalance(root);
    }
    boolean isBalance(TreeNode root){
        if(root==null){
            return true;
        }
        if(Math.abs(getLen(root.left)-getLen(root.right))>1){
            return false;
        }else{
            return isBalance(root.left)&&isBalance(root.right);
        }

    }
    int getLen(TreeNode root){
        if(root==null){
            return 0;
        }
        return Math.max(getLen(root.left),getLen(root.right))+1;

    }

}

全部评论

相关推荐

头像
05-09 00:54
已编辑
前端工程师
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务