LeetCode 集錦(二十六) - 第 110 題 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. 

 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. 
複製代碼

翻譯:

給定一個二叉樹,判斷它是否高度平衡。 對於該問題,定義高度平衡二叉樹爲: 一種二叉樹,其中每一個節點的兩個子樹的深度相差不超過1。 示例1: 給定以下樹[3,9,20,null,null,15,7]:node

3
  / \
 9  20
   /  \
  15   7 
複製代碼

返回 true 示例2: 給定以下樹[1,2,2,3,3,null,null,4,4]:git

1
     / \
    2   2
   / \
  3   3
 / \
4   4
複製代碼

返回 falsegithub


解題思路

本題是相對而言比較簡單,判斷一棵樹是否是平衡二叉樹。平衡二叉樹的限制條件就是一個樹的每一個節點的左右子節點的深度相差不能超過1。按照這個思路,其實能夠遞歸遍歷出每一個樹節點的深度,判斷左右節點是否差過1,就ok了bash

解題方法

  1. 按照分治法優化

    public boolean isBalanced(TreeNode root) {
         if (root == null) {
             return true;
         }
         return deap(root) != -1;
    
     }
    
     private int deap(TreeNode root) {
         if (root == null) {
             return 0;
         }
    
         int left = deap(root.left) + 1;
    
         int right = deap(root.right) + 1;
         if (left == 0 || right == 0) {
             return -1;
         }
         if (Math.abs(left - right) > 1) {
             return -1;
         }
         return Math.max(left, right);
     }
    複製代碼

    時間複雜度: 該方案用了遍歷的方式,因此爲O(n)=O(n)ui

    空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度O(n)=O(1)this

總結

本題的大體解法如上所訴,經過遍歷的方式,來獲取左右節點的高度,判斷是否相差1,其實這邊還能夠優化,那就是獲取高度的時候是否是0,若是不符合了就不須要在走下面的方式了。spa

歡迎關注個人博客-FightCrap翻譯

相關文章
相關標籤/搜索