zoukankan      html  css  js  c++  java
  • LeetCode 110. Balanced Binary Tree

    原题链接在这里:https://leetcode.com/problems/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 left and right subtrees of every node differ in height by no more than 1.

    Example 1:

    Given the following tree [3,9,20,null,null,15,7]:

        3
       / 
      9  20
        /  
       15   7

    Return true.

    Example 2:

    Given the following tree [1,2,2,3,3,null,null,4,4]:

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    Return false.

    题解:

    Get 最大深度.如果左右最大深度相差大于一,则返回-1. 若是已有左或者右的返回值为-1, 即返回-1.

    最后看返回到root时是否为一个负数,若是负数则不是balanced, 若是正数,则返回了最大深度,是balanced.

    Time Complexity: O(n).

    Space: O(log n), n is number of nodes in the tree.

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     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         return maxDepth(root) >= 0; 
    13     }
    14     
    15     private int maxDepth(TreeNode root){
    16         if(root == null){
    17             return 0;
    18         }
    19         int leftDepth = maxDepth(root.left);
    20         int rightDepth = maxDepth(root.right);
    21         if(leftDepth == -1 || rightDepth == -1 || Math.abs(leftDepth - rightDepth) > 1){
    22             return -1;
    23         }
    24         return Math.max(leftDepth, rightDepth) + 1;
    25     }
    26 }

    类似Maximum Depth of Binary Tree.  

  • 相关阅读:
    Bootstrap-CL:警告
    Bootstrap-CL:略缩图
    Bootstrap-CL:页面标题
    Bootstrap-CL:超大屏幕
    Bootstrap-CL:徽章
    Bootstrap-CL:标签
    Bootstrap-CL:分页
    Bootstrap-CL:面包屑导航
    Bootstrap-CL:导航栏
    Bootstrap-CL:导航元素
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824994.html
Copyright © 2011-2022 走看看