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 }
  • 相关阅读:
    第一阶段冲刺09
    英文单词统计
    第一阶段冲刺08
    暑假生活第二周
    暑假生活第一周
    大道至简读书笔记03
    个人总结15
    大道至简读书笔记02
    计算最长英语单词链
    个人总结14
  • 原文地址:https://www.cnblogs.com/feiling/p/3263550.html
Copyright © 2011-2022 走看看