110 Balanced Binary Tree


title: Balanced Binary Tree
tags:
- balanced-binary-tree
- No.110
- simple
- tree
- depth-first-search
- recursive


Description

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.

Corner Cases

  • empty root

Solutions

Queue

Recursively solve height and compare them. Running time is O(V) for dfs.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private boolean flag = true;
    public boolean isBalanced(TreeNode root) {
        if (root == null) {return true;}
        int hl = h(root.left);
        int hr = h(root.right);
        flag   = flag & (hl == hr || hl == hr + 1 || hl == hr - 1);
        return flag;        
    }
    private int h(TreeNode x) {
        if (x == null) {return 0;}

        int hl = h(x.left);
        int hr = h(x.right);
        flag = flag & (hl == hr || hl == hr + 1 || hl == hr - 1);

        return (hl > hr) ? hl + 1 : hr + 1;
    }
}

你可能感兴趣的:(110 Balanced Binary Tree)