zoukankan      html  css  js  c++  java
  • Balanced Binary Tree

    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.

    the tree is only balanced if:

    1. The left and right subtrees' heights differ by at most one, AND
    2. The left subtree is balanced, AND
    3. The right subtree is balanced

    so tree like this is also balanced:

                      o

                    /

                  o      o

                /      /  

              o      o       o

                   /

                 o

     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         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         return (check(root) != -1);
    15     }
    16     public int check(TreeNode node){
    17         if(node == null) return 0;
    18         else{
    19             int left = check(node.left);
    20             if(left == -1) return -1;
    21             int right = check(node.right);
    22             if(right == -1) return -1;
    23             if(Math.abs(left - right) < 2) return (left > right ? left : right) + 1;
    24             else return -1;
    25         }
    26     }
    27 }
  • 相关阅读:
    【ZJOI2007】棋盘制作 BZOJ1057
    【ZJOI2008】 树的统计 count
    【JSOI2007】麻将 bzoj 1028
    【省选】省选黄色预警
    【ZJOI2013】k大数查询 BZOJ 3110
    【HNOI2008】Cards BZOJ 1004
    【JSOI2010】Group 部落划分 BZOJ 1821
    NOIp2014 解题报告
    CH Round #56
    CH Round #55
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3316828.html
Copyright © 2011-2022 走看看