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
---
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
return self.dfs(root)[1]
def dfs(self, node: TreeNode) -> Tuple[int, bool]:
if not node:
return (0, True)
left = self.dfs(node.left)
if not left[1]:
return (0, False)
right = self.dfs(node.right)
if not right[1]:
return (0, False)
if abs(left[0] - right[0]) > 1:
return (0, False)
return (1 + max(left[0], right[0]), True)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Pair {
int height;
boolean balanced;
public Pair(int h, boolean b) {
height = h;
balanced = b;
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
return dfs(root).balanced;
}
private Pair dfs(TreeNode node) {
if (node == null) {
return new Pair(0, true);
}
Pair left = dfs(node.left);
if (!left.balanced) {
return new Pair(0, false);
}
Pair right = dfs(node.right);
if (!right.balanced) {
return new Pair(0, false);
}
if (Math.abs(left.height - right.height) > 1) {
return new Pair(0, false);
}
return new Pair(1 + Math.max(left.height, right.height), true);
}
}