110. Balanced Binary Tree

Link

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.

Solution

有兩種做法

Way 1 ( top -down): T: O(N^2) worst case

  1. 建立一個計算node的depth的helper function

  2. 如果node.left & node.right 的depth差距在1以下,就往下再檢查node.left跟node.right其子樹的depth差距

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        if(Math.abs(depth(root.right) - depth(root.left)) <= 1){
            return isBalanced(root.right) && isBalanced(root.left); 
        }
        return false;
    }
    
    public int depth(TreeNode node){
        if(node == null) return 0;
        else{
            return Math.max(depth(node.left), depth(node.right)) + 1;
        }
        
    }

Way 2( button-up):

  1. 在計算depth時順便判斷是否左右子樹差距是在1以內,若不是返為-1告知不是

T: O(N)

    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }  
        return dfsDepth(root) != -1;
    }
    
    public int dfsDepth(TreeNode node){
        if(node == null) return 0;
        int leftDepth = dfsDepth(node.left);
        if(leftDepth == -1) return -1;
        int rightDepth = dfsDepth(node.right);
        if(rightDepth == -1) return -1;
        if(Math.abs(rightDepth - leftDepth) > 1) return -1;  
        return Math.max(leftDepth , rightDepth) + 1;
    }

Last updated

Was this helpful?