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 }
  • 相关阅读:
    SharePoint 2013 中的 URL 和标记
    负载均衡
    高可用集群
    客户端访问浏览器的流程
    【SDOI2014】数表
    【UR #5】怎样跑得更快
    【BZOJ2820】YY的GCD
    【SDOI2017】数字表格
    Codeforces 548E Mike ans Foam (与质数相关的容斥多半会用到莫比乌斯函数)
    【BZOJ2693】jzptab
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3316828.html
Copyright © 2011-2022 走看看