Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)

Автор: Back To Back SWE

Загружено: 2019-01-21

Просмотров: 101160

Описание:

Free 5-Day Mini-Course: https://backtobackswe.com
Try Our Full Platform: https://backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions

Question: Write a program that takes the root of a binary tree as input and checks whether the tree is height-balanced.

A tree is height balanced if for each node in the tree, the difference in the height of its left and right subtrees is at most one.


Approach 1 (Get Height Of Tree Rooted At Each Node)

We can perform a traversal of the tree and at each node get the height of its left and right subtrees.

This wastes time as we will be repeating work and the traversal of nodes.


Approach 2 (Drill Down With Recursion And Respond Back Up)

We can notice that we don't need to know the heights of all of the subtrees all at once.

All we need to know is whether a subtree is height balanced or not and the height of the tree rooted at that node, not information about any of its descendants.

Our base case is that a null node (we went past the leaves in our recursion) is height balanced and has a height of -1 since it is an empty tree.

So the key is that we will drive towards our base case of the null leaf descendant and deduce and check heights on the way upwards.


Key points of interest:

1.) Is the subtree height balanced?
2.) What is the height of the tree rooted at that node?


Complexities

Time: O( n )

This is a postorder traversal (left right node) with possible early termination if any left subtree turns out unbalanced and an early result bubbles back up.

At worst we will still touch all n nodes if we have no early termination.

Space: O( h )

Our call stack (from recursion) will only go as far deep as the height of the tree, so h (the height of the tree) is our space bound for the amount of call stack frames that we will create

++++++++++++++++++++++++++++++++++++++++++++++++++

HackerRank:    / @hackerrankofficial  

Tuschar Roy:    / tusharroy2525  

GeeksForGeeks:    / @geeksforgeeksvideos  

Jarvis Johnson:    / vsympathyv  

Success In Tech:    / @successintech  

++++++++++++++++++++++++++++++++++++++++++++++++++

This question is number 10.1 in "Elements of Programming Interviews" by Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash.

Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Подсчитайте общее количество уникальных двоичных деревьев поиска — n-ное каталонское число (динам...

Подсчитайте общее количество уникальных двоичных деревьев поиска — n-ное каталонское число (динам...

Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.

Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.

Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)

Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)

AVL Trees & Rotations (Self-Balancing Binary Search Trees)

AVL Trees & Rotations (Self-Balancing Binary Search Trees)

Мой мозг после 569 проблем с Leetcode

Мой мозг после 569 проблем с Leetcode

The Change Making Problem - Fewest Coins To Make Change Dynamic Programming

The Change Making Problem - Fewest Coins To Make Change Dynamic Programming

Balanced Binary Tree - Leetcode 110 - Trees (Python)

Balanced Binary Tree - Leetcode 110 - Trees (Python)

Test If A Binary Tree Is Symmetric (

Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)

Compute The Next Permutation of A Numeric Sequence - Case Analysis (

Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)

Lowest Common Ancestor of a binary tree | Leetcode #236

Lowest Common Ancestor of a binary tree | Leetcode #236

Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm (

Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)

Теренс Тао о том, как Григорий Перельман решил гипотезу Пуанкаре | Лекс Фридман

Теренс Тао о том, как Григорий Перельман решил гипотезу Пуанкаре | Лекс Фридман

Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs

Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs

Сбалансированное двоичное дерево — Leetcode 110 — Python

Сбалансированное двоичное дерево — Leetcode 110 — Python

I gave 127 interviews. Top 5 Algorithms they asked me.

I gave 127 interviews. Top 5 Algorithms they asked me.

Простейший трюк обхода двоичного дерева для прямого порядка, прямого порядка и обратного порядка

Простейший трюк обхода двоичного дерева для прямого порядка, прямого порядка и обратного порядка

Откуда в трубке телефона берётся гудок?

Откуда в трубке телефона берётся гудок?

Понимание B-деревьев: структура данных, лежащая в основе современных баз данных

Понимание B-деревьев: структура данных, лежащая в основе современных баз данных

10.1 AVL Tree - Insertion and Rotations

10.1 AVL Tree - Insertion and Rotations

Итеративный и рекурсивный — симметричный обход двоичного дерева — Leetcode 94 — Python

Итеративный и рекурсивный — симметричный обход двоичного дерева — Leetcode 94 — Python

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]