From 817cbb57a2ec608784a69dce949bf3e59ef72c65 Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Thu, 3 Aug 2023 15:55:38 -0700 Subject: [PATCH] Create bst_is_balanced.py --- trees/bst_is_balanced.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 trees/bst_is_balanced.py diff --git a/trees/bst_is_balanced.py b/trees/bst_is_balanced.py new file mode 100644 index 0000000..7acb0b0 --- /dev/null +++ b/trees/bst_is_balanced.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + + +def height(root): + + if not root: + return -1 + + return 1 + max(height(root.left), height(root.right)) + + +def is_balanced(root): + + if not root: + return True + + return abs(height(root.left) - height(root.right)) < 2 and \ + is_balanced(root.left) and is_balanced(root.right) +