ycliper

Популярное

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

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

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

Топ запросов

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

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

lowest common ancestor

binary tree

binary search tree

lowest ancestor binary tree

Back To Back SWE

Software Engineering

computer science

programming

programming interviews

coding interviews

coding questions

algorithms

algorithmic thinking

Google internship

Facebook internship

software engineering internship

swe internship

big n companies

Автор: Back To Back SWE

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

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

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

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)

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

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

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

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

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

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

Lowest Common Ancestor of a Binary Tree 3 || Leetcode 1650 || 2 Variant Questions Big Tech Asks

Lowest Common Ancestor of a Binary Tree 3 || Leetcode 1650 || 2 Variant Questions Big Tech Asks

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

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

Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction

Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction

LOWEST COMMON ANCESTOR OF A BINARY TREE III [PYTHON]

LOWEST COMMON ANCESTOR OF A BINARY TREE III [PYTHON]

Binary lifting: Dynamic Programming on Trees

Binary lifting: Dynamic Programming on Trees

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

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

Похудей на 45 КГ, Выиграй $250,000!

Похудей на 45 КГ, Выиграй $250,000!

LOWEST COMMON ANCESTOR OF A BINARY TREE I | PYTHON | LEETCODE 236

LOWEST COMMON ANCESTOR OF A BINARY TREE I | PYTHON | LEETCODE 236

Игра, опередившая время на десятилетия  | The Movies 2005

Игра, опередившая время на десятилетия | The Movies 2005

Comedy Club: Курсы альфа-самца | Кравец, Шальнов, Бутусов @ComedyClubRussia

Comedy Club: Курсы альфа-самца | Кравец, Шальнов, Бутусов @ComedyClubRussia

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



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



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