Популярное

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

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

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

Топ запросов

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

Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)

Автор: Back To Back SWE

Загружено: 2019-04-02

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

Описание:

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: Given the root of a binary tree and 2 references of nodes that are in the binary tree, find the lowest common ancestor of the 2 nodes. The nodes do not have parent pointers.

The Approach

So there are many modulations of this problem where you can build a hashtable and make parent pointers, etc. We will focus on the recursive solution.


The Algorithm

The key is that we want to root ourselves at a node and then search left and then right for either of the 2 nodes given.

If we see either node, we will return it, if we do not find the node in a subtree search the value of null will be returned and bubbled up.

After we search both left and right we ask ourselves what our results mean.

If we found nothing to the left, we just bubble up what is on the right (whatever that search result may be). This node we sit at cannot be the LCA since the left and right did not yield the 2 nodes we want.

If we found nothing to the right, we just bubble up what is on the left (whatever that search result may be). This node we sit at cannot be the LCA since the left and right did not yield the 2 nodes we want.

If both the right and left result are not null, we have found our LCA.


Why?

We know it is an ancestor at the least but we definitely know it is the lowest common ancestor because we went bottom upwards, whatever we hit will be the LCA and it will bubble up.


Complexities

Time: O( n )

We will be touching the whole tree in the search, there are n nodes in the tree and we do O(1) work at each node. There are not exactly n calls though but I need to double check this...I need to solve the recurrence but oh well...we know it will stay linear in the asymptotic regard.

Space: O( h )

Stack usage at maximum will be the trees height. Worst case would be O(n) if our tree is skewed purely to the left or right and we need to find deep nodes. But n IS h in that case. But we say O( n ) in that case since it is more accurate to what is happening, the tree's size in nodes dominating the height.

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

HackerRank:    / @hackerrankofficial  

Tuschar Roy:    / tusharroy2525  

GeeksForGeeks:    / @geeksforgeeksvideos  

Jarvis Johnson:    / vsympathyv  

Success In Tech:    / @successintech  

Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)

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

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

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

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

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

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

array(10) { [0]=> object(stdClass)#5651 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "uXBnyYuwPe8" ["related_video_title"]=> string(71) "The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse" ["posted_time"]=> string(19) "6 лет назад" ["channelName"]=> string(16) "Back To Back SWE" } [1]=> object(stdClass)#5624 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "i-FFVM4cIXQ" ["related_video_title"]=> string(138) "База по Базам Данных - Storage (Индексы, Paging, LSM, B+-Tree, R-Tree) | Влад Тен Систем Дизайн" ["posted_time"]=> string(21) "5 дней назад" ["channelName"]=> string(15) "Влад Тен" } [2]=> object(stdClass)#5649 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "suj1ro8TIVY" ["related_video_title"]=> string(94) "Serialize & Deserialize A Binary Tree - Crafting Recursive Solutions To Interview Problems" ["posted_time"]=> string(19) "6 лет назад" ["channelName"]=> string(16) "Back To Back SWE" } [3]=> object(stdClass)#5656 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "LU4fGD-fgJQ" ["related_video_title"]=> string(77) "Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)" ["posted_time"]=> string(19) "6 лет назад" ["channelName"]=> string(16) "Back To Back SWE" } [4]=> object(stdClass)#5635 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "vRwi_UcZGjU" ["related_video_title"]=> string(62) "AVL Trees & Rotations (Self-Balancing Binary Search Trees)" ["posted_time"]=> string(19) "5 лет назад" ["channelName"]=> string(16) "Back To Back SWE" } [5]=> object(stdClass)#5653 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "Nc8Pxx24f-k" ["related_video_title"]=> string(120) "Аксиома выбора: как Георг Кантор чуть не сломал математику [Veritasium]" ["posted_time"]=> string(19) "3 дня назад" ["channelName"]=> string(10) "Vert Dider" } [6]=> object(stdClass)#5648 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "O4Hyb5HtD3s" ["related_video_title"]=> string(103) "Что говорят СМИ Ирана о войне с Израилем (English subtitles) @Max_Katz" ["posted_time"]=> string(22) "22 часа назад" ["channelName"]=> string(19) "Максим Кац" } [7]=> object(stdClass)#5658 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "qMQLnkTOkCo" ["related_video_title"]=> string(173) "Израиль vs Иран: чья армия сильнее? | «Железный купол», ПВО, МОССАД vs дроны, самолеты, прокси" ["posted_time"]=> string(21) "1 день назад" ["channelName"]=> string(8) "varlamov" } [8]=> object(stdClass)#5634 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "SBqOLUJEgC0" ["related_video_title"]=> string(71) "Путин встретился с главами мировых СМИ" ["posted_time"]=> string(24) "10 часов назад" ["channelName"]=> string(13) "AKIpress news" } [9]=> object(stdClass)#5652 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "OI7_e41eOy0" ["related_video_title"]=> string(166) "✓ Веревку вокруг Земли удлинили на 1 см. Пройдёт ли человек? | Ботай со мной #092 | Борис Трушин" ["posted_time"]=> string(21) "4 года назад" ["channelName"]=> string(23) "Борис Трушин" } }
The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse

The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse

База по Базам Данных - Storage (Индексы, Paging, LSM, B+-Tree, R-Tree) | Влад Тен Систем Дизайн

База по Базам Данных - Storage (Индексы, Paging, LSM, B+-Tree, R-Tree) | Влад Тен Систем Дизайн

Serialize & Deserialize A Binary Tree - Crafting Recursive Solutions To Interview Problems

Serialize & Deserialize A Binary Tree - Crafting Recursive Solutions To Interview Problems

Test If A Binary Tree Is Height Balanced (

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

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

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

Аксиома выбора: как Георг Кантор чуть не сломал математику [Veritasium]

Аксиома выбора: как Георг Кантор чуть не сломал математику [Veritasium]

Что говорят СМИ Ирана о войне с Израилем (English subtitles) @Max_Katz

Что говорят СМИ Ирана о войне с Израилем (English subtitles) @Max_Katz

Израиль vs Иран: чья армия сильнее? | «Железный купол», ПВО, МОССАД vs дроны, самолеты, прокси

Израиль vs Иран: чья армия сильнее? | «Железный купол», ПВО, МОССАД vs дроны, самолеты, прокси

Путин встретился с главами мировых СМИ

Путин встретился с главами мировых СМИ

✓ Веревку вокруг Земли удлинили на 1 см. Пройдёт ли человек? | Ботай со мной #092 | Борис Трушин

✓ Веревку вокруг Земли удлинили на 1 см. Пройдёт ли человек? | Ботай со мной #092 | Борис Трушин

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



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



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