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 }
  • 相关阅读:
    iOS的几种动画使用
    iOS工程师必备技能
    网络数据的下载(NSUrlconnection异步下载和NSstring同步下载)和UI界面数据的刷新(都是抛弃第三方库的一些本质)
    GCD定时器
    iOS开发的小技巧
    站在巨人的肩膀上
    跳转系统设置相关界面的方法
    微信分享
    网站 、内容
    加水印
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3316828.html
Copyright © 2011-2022 走看看