ycliper

Популярное

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

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

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

Топ запросов

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

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

Автор: Back To Back SWE

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

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

Описание: 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.

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)

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

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

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

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

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

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

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

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

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

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

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

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

10.1 AVL Tree - Insertion and Rotations

10.1 AVL Tree - Insertion and Rotations

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

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

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)

The Hairy Ball Theorem

The Hairy Ball Theorem

Balanced Binary Tree - Leetcode 110 - Trees (Python)

Balanced Binary Tree - Leetcode 110 - Trees (Python)

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

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

Test If A Binary Tree Is Symmetric (

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

Алгоритмы и структуры данных ФУНДАМЕНТАЛЬНЫЙ КУРС от А до Я. Графы, деревья, хеш таблицы и тд

Алгоритмы и структуры данных ФУНДАМЕНТАЛЬНЫЙ КУРС от А до Я. Графы, деревья, хеш таблицы и тд

Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable

Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable

7. Binary Trees, Part 2: AVL

7. Binary Trees, Part 2: AVL

Everyday Habits That Quietly Make You Less Intelligent

Everyday Habits That Quietly Make You Less Intelligent

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

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

Alex Honnold on Free-Climbing Taipei 101 Skyscraper Live on Netflix & the Last Time He Felt Scared

Alex Honnold on Free-Climbing Taipei 101 Skyscraper Live on Netflix & the Last Time He Felt Scared

L15. Check for Balanced Binary Tree | C++ | Java

L15. Check for Balanced Binary Tree | C++ | Java

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

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

Самая длинная общая подпоследовательность (2 строки) — динамическое программирование и конкурирую...

Самая длинная общая подпоследовательность (2 строки) — динамическое программирование и конкурирую...

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



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



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