zoukankan      html  css  js  c++  java
  • leetcode -- Balanced Binary Tree TODO

    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 everynode never differ by more than 1.

     [解题思路]

    检查每个node是否是balanced,大数据集挂掉了

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public boolean isBalanced(TreeNode root) {
    12         // Start typing your Java solution below
    13         // DO NOT write main() function
    14         if(root == null){
    15             return true;
    16         }
    17         
    18         return checkBalance(root);
    19     }
    20     
    21     public boolean checkBalance(TreeNode node){
    22         if(node == null){
    23             return true;
    24         }
    25         int left = getDepth(node.left);
    26         int right = getDepth(node.right);
    27         if(Math.abs(left - right) > 1){
    28             return false;
    29         }
    30         return checkBalance(node.left) && checkBalance(node.right);
    31     }
    32     
    33     public int getDepth(TreeNode node){
    34         if(node == null){
    35             return 0;
    36         }
    37         int left = getDepth(node.left);
    38         int right = getDepth(node.right);
    39         return Math.max(left, right) + 1;
    40     }
    41 }
  • 相关阅读:
    JAVA EE 第一阶段项目问题
    车辆管理系统之开始自己的任务(三)
    车辆管理系统之搭建框架 添加必要的数据 安装svn(二)
    车辆管理系统之分析信息建表(一)
    牛客问题
    记录---base64
    JAVA EE 第一阶段考试
    简单ssh框架整合
    Struts2拦截器
    Struts2文件上传
  • 原文地址:https://www.cnblogs.com/feiling/p/3263550.html
Copyright © 2011-2022 走看看