algorithm,recursion,binary-tree , How to find lowest common ancestor in binary tree using bottom up recursion [closed]

## Question:

Tag: algorithm,recursion,binary-tree

I am having a hard time understanding how to find lowest common ancestor in binary tree using bottom up recursion.

HERE is the solution which looks very neat. I tried drying running it on a small tree but no luck.

Can someone please help with this.

Answer:

The algorithm you linked to is reproduced below, in case the link changes:

public static Tree findLowestCommonAncestor(Tree root, Tree p, Tree q)
{
if (root == null)
return null;

if (root == p || root == q)
return root;

Tree left = findLowestCommonAncestor(root.left, p, q);
Tree right = findLowestCommonAncestor(root.right, p, q);

if (left != null && right != null)
return root;

if (left != null)
return left;
else
return right;
}

It works like this. The key observation is that if we consider a node n that is an ancestor of p and q, and ask whether it's the lowest common ancestor, there are basically three possibilities:

1. p and q are both descendants of the left child of n, but not the right child;
2. p and q are both descendants of the right child of n, but not the left child;
3. p and q are both descendants of both children of n.

This is the idea behind the whole algorithm. We start at the root, and work our way down. We recursively find the LCA of p and q from the left child l of the current node, and the right child r of the current node.

If the left-hand search returns something, but the right-hand search doesn't, then that means the left-hand search found the right value (because the answer is lower down than the current node, and either l itself or a descendant of l). Similarly if the right-hand search returns something, but the left-hand search doesn't.

If the left-hand and right-hand searches both return something, then p and q are both descendants of n. That means that we can return n as the LCA: it can't be anything lower, because otherwise we'd have found it earlier in the recursive search; and it is a common ancestor, so it must therefore be the lowest one.

(The language isn't particularly helpful, by the way: I'd have said that the ancestor you want is the highest one in the tree, but in what you're looking at, lowest seems to mean nearest to the root.)

# Related:

## How to reduce time to find the n-th place from consecutive digits number for less than 1 second

php,algorithm,digits
I'm following the programming test, and there are questions like this From this consecutive digits: 123456789101112131415161718192021.... For example The 10th digit is 1 The 11th digit is 0 and so on What is the 1,000,000th digit? What is the 1,000,000,000th digit? What is the 1,000,000,000,000th digit? Your solution should run...

## Looking for a particular algorithm for numerical integration

algorithm,numerical-methods,numerical,numerical-integration
Consider the following differential equation f(x) = g'(x) I have a build a code that spits out values of the function f(x) for the variable x, where x goes from 0 to very large. Now, I'm looking for a scheme that will analyse these values of f(x) in order to...

## BSTD inorder traversal produces erroneous behaviour

java,debugging,recursion,immutability
I have a BSTD implementation which is inserting values incorrectly and I can't find for the life of me what is going on. EXPECTED ACTUAL -------- ---------- Alex Janice Carlos Janice Elton Janice Janice Zidane Zidane Zidane Implementation private Node<K,E> insert(Node<K,E> node, K key, E elem) { if (node ==...

## Decremented value called in the recursion in Haskell

string,function,haskell,recursion,parameters
So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

## Python RuntimeError: maximum recursion depth exceeded in cmp

python,list,dictionary,recursion
I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

## Does there exist an algorithm for iterating through all strings that conform to a particular regex?

c#,regex,algorithm
I'm making a script to try and hack into an account whose login password is at least 8 characters long and includes at least 1 number, 1 special character and 1 capital letter. I will use brute force. Is there a compact, elegant and efficient way to iterate through every...

## Stopping condition on a recursive function - Haskell

string,function,haskell,if-statement,recursion
So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

## Algorithm for [inclusive/exclusive]_scan in parallel proposal N3554

c++,algorithm,parallel-processing,c++14
Proposal N3554 (A Parallel Algorithms Library) for C++14, proposes (among other things), what seem to be parallel versions of the current std::partial_sum, e.g.: template< class ExecutionPolicy, class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator inclusive_scan( ExecutionPolicy &&exec, InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); With the explanation Effects: For each...

## Recusively count children nodes in binary tree

java,recursion,binary-tree,nodes
So my coding exercise is given the reference to the node count its children. I've decided to use recursion and I was wondering is this a elegant way to do this: Let's assume there is class Node which represent every node in the tree: public Node { int data: Node...

## Ranking with time weighting

python,algorithm,sorting,math
I am looking for a basic algorithm that gives more weigh to the recent reviews. So, the output value of the algorithm is mutable. For example, two reviews with exactly the same score, will have a different ranking based on the timestamp of the creation. Review_1 Score 10 creation 10/5/2014...

## How does ((a++,b)) work? [duplicate]

c,function,recursion,comma
This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

## Should checking loop conditions be counted towards total number of comparisons?

c++,algorithm,sorting,c++11
I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

## Reverse Linked List recursively, why it is wrong

recursion
Problem: Reverse a singly linked list recursively. I know how to solve this problem, but one of my recursive methods is wrong, I can not figure out what's wrong with this code. Could anyone figure out that? Thanks a lot! Test case: Input: [1,2,3] Output: [3,1] Expected: [3,2,1] public class...

## sum of Digits through Recursion

java,function,recursion,sum,digit
I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

## EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread

c++,multithreading,sorting,recursion
I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

## Scala first program issue

scala,recursion,case,frequency
I have just started to learn Scala after some experience with functional programming in other languages. def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{ case _ => freq(c, y.filter(_ == c), list :: List((count(c,y),c))) case nil => list } In the above code I am getting an error when trying...

## Knapsack with unbounded items

algorithm,dynamic-programming,knapsack-problem
I am familiar with the 0-1 knapsack problem and when you are given a certain number of copies from each item but I can figure out how to solve it when you are given infinite copies of each item using dynamic programming. I am trying to solve it by hand...

## Algorithmic big o order of growth code

algorithm,discrete-mathematics
I'm doing an online course and i'm stuck on this question. I know there are similar questions but they don't help me. What is the order of growth of the worst case running time of the following code fragment as a function of N? int sum = 0; for (int...

## Recurions: simple spiral with python turtle

python,recursion,turtle-graphics
I'm trying to recreate a function spiral() using recursion that takes the parameters initLen (pixel length of first side), N (angle connecting segments), and mult (a float amount indicating how much bigger/smaller each segment should be after each turn - ex: mult = 0.5 means each segment would be half...

## Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime
If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

## Understanding Big-Ω (Big-Omega) notation

algorithm,big-o
I was doing some reading on logarithms and the rate of growth of the running time of algorithms. I have, however, a problem understanding the Big-Ω (Big-Omega) notation. I know that we use it for 'asymptotic lower bounds', and that we can express the idea that an algorithm takes at...

## R: split string into numeric and return the mean as a new column in a data frame

r,recursion,dplyr,strsplit
I have a large data frame with columns that are a character string of numbers such as "1, 2, 3, 4". I wish to add a new column that is the average of these numbers. I have set up the following example: set.seed(2015) library(dplyr) a<-c("1, 2, 3, 4", "2, 4,...

## How to give mathemarical proof or support my answer through reasoning as a general case?

algorithm
You are managing a software project that involves building a computer-assisted instrument for medical surgery. The exact placement of the surgical knife is dependent on a number of different parameters, usually at least 25, sometimes more. Your programmer has developed two algorithms for positioning the cutting tool, and is seeking...

## Binary Search - Best and worst case

algorithm,data-structures
In an exam I see a question: Which one of the following is true? For a binary search, the best-case occurs when the target item is in the beginning of the search list. For a binary search, the best-case occurs when the target is at the end of the search...

## Best way to extract ODD digits from a binary number

algorithm,bit-manipulation
Given a 64 bit number, I need to extract every other bit from it, and convert it into a number: decimal: 357 binary: 0000 0001 0110 0101 odd bits: 0 0 0 1 1 0 1 1 decimal: 27 Any idea of a good algorithmic way to do it? And...

## Eloquent Javascript: DOM Animation snippet

javascript,animation,dom,recursion,requestanimationframe
I'm trying to understand everything that is happening in this little code example in Eloquent Javascript: The Document Object Model (Chapter 13), but I'm not clear on where exactly the value for "time" is being passed into the animate() function before the function itself gets passed into requestAnimationFrame(). What exactly...

## Reversing an integer using recursive method in C++

c++,recursion
I have this recursive function to reverse a positive integer. Anybody having an efficient algorithm to do the task using fewer recursive calls (but still using recursion), please post here! int countDigit (const int & _X) { if (_X < 10) return 1; return (countDigit(_X / 10) + 1); }...

## Recursion of Linked List

java,recursion,nullpointerexception,linked-list
When given an array of integers, I'm trying to change each element with the product of the integers before it. For example, int[] array = {2,2,3,4}; is now: {2, 4, 12, 48}; I added each element to a LinkedList, and I'm trying to do this recursively. This is what I...

## Disconnect all vertices in a graph - Algorithm

algorithm,graph
I am looking for an algorithm that finds minimal subset of vertices such that by removing this subset (and edges connecting these vertices) from graph all other vertices become unconnected (i.e. the graph won't have any edges). Is there such algorithm? If not: Could you recommend some kind of heuristics...

## Recursive solution doesn't iterate correctly

ruby,algorithm,search,recursion
I'm working through a toy problem in Ruby: how to produce all possible 10-digit phone numbers where each successive number is adjacent to the last on the keypad. I've represented the adjacent relationships between numbers, and have a recursive function, but my method isn't iterating through the whole solution space....

## How to flatten a structure of embedded Set and Hash

ruby,recursion
I would like to convert an embedding structure into a flat one. An embedding structure is a set of 0 or more objects, such as: a string or a hash having some string as key and some other embedding structure as value. A flat structure is a set of arrays...

## Python recursive function not recursing

python,recursion
I'm trying to solve a puzzle, which is to reverse engineer this code, to get a list of possible passwords, and from those there should be one that 'stands out', and should work function checkPass(password) { var total = 0; var charlist = "abcdefghijklmnopqrstuvwxyz"; for (var i = 0; i...

## Longest Increasing Subsequence code in O(N)?

python,algorithm,time-complexity,longest-substring
Someone asked me a question Find the longest alphabetically increasing or equal string composed of those letters. Note that you are allowed to drop unused characters. So ghaaawxyzijbbbklccc returns aaabbbccc. Is an O(n) solution possible? and I implemented it code [in python] s = 'ghaaawxyzijbbbklccc' lst = [[] for i...

## Determining if a graph has a cycle without using DFS

algorithm,graph,cycle,dfs
I came around one of those questions in my exams: Topologocial sorting using Kahn's Algorithm requires the graph to be DAG (Directed Acyclic Graph). How can we determine if a graph contains no cycles without using DFS/BFS first? I am trying to answer that for too long now and I...

## Travels using graph

c++,algorithm,graph
Someone can help me to think in the better way to adapt Dijkstra's Algorithm in these conditions? All I thought didn't was good. Example of input: GP4578 MADRID 01:00 PORTO 02:00 IK6587 PORTO 03:00 VALENCIA 05:00 05:30 TENERIFE 08:00 AB5874 VALENCIA 05:40 BERLIM 10:00 "VALENCIA 05:00 05:30" This is a...

## Getting Wrong Answer in “Longest non regular parentheses sub-sequence ”codechef june cook off

algorithm
I attended a programming competition(it has ended now). I don't know why my solution is giving WA, I read the editorial, saw other people solution but unable to find a flaw in my solution. Obviously I am missing somewhere. Please help! Question Link My Solution My approach If the pattern...

## Explain the time complexity of these grouping functions

c++,algorithm,inheritance,time-complexity
Here I have 800 derived classes of Base and a list of 8000000 objects of these types, which can be of any order. The goal is to separate the list into the 800 types as efficiently as possible. Here I have written two functions to do that. The first is...

## Reverse ^ operator for decryption

c,algorithm,security,math,encryption
I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

## 3 X 3 magic square recursively

c++,algorithm,math,recursion
I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

## T-SQL Ordering a Recursive Query - Parent/Child Structure

sql,tsql,recursion,order,hierarchy
I am trying (and failing) to correctly order my recursive CTE. My table consists of a parent-child structure where one task can relate to another on a variety of different levels. For example I could create a task (this is the parent), then create a sub-task from this and then...

## R: recursive function to give groups of consecutive numbers

r,if-statement,recursion,vector,integer
Given a sorted vector x: x <- c(1,2,4,6,7,10,11,12,15) I am trying to write a small function that will yield a similar sized vector y giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15): > y...

## Dynamic programming: how to design algorithm for when there are two factors to consider?

algorithm,optimization,dynamic-programming,frequency
I have the following problem and I only have a slight idea about it: Consider a tape storage problem. Given n files of length l1,...,ln and frequencies with which they are accessed f1,...,fn, where sum of all frequencies is 1 and 0<fi<1. "Optimal" means to minimize the average retrieval time...

## Javascript: Detailed differences between !variable and variable == false?

javascript,algorithm
I accidentally got undefined == true and undefined == false that both of them returns false. But !undefined returns true. And this is the question: What's the algorithmic difference(s) between !someVariable and someVariable == false? If i want to explain it more, type undefined == false ? 't' : 'f'...

## What is this algorithm mapping coordinates to numbers called?

algorithm,coordinates,coordinate-systems,coordinate
I'm writing a program for visualizing crystals. As a part of the program, I have to generate all different basic points in a lattice structure. For those that aren't familiar with crystallography, you can find the most general cases of these structures here: https://en.wikipedia.org/wiki/Hermann%E2%80%93Mauguin_notation#Lattice_types The problem was that I wanted...

## Recursive Lag Column Calculation in SQL

sql,sql-server,recursion
I am trying to write a procedure that inserts calculated table data into another table. The problem I have is that I need each row's calculated column to be influenced by the result of the previous row's calculated column. I tried to lag the calculation itself but this does not...

## Find the shortest path sum in a matrix. Is Dijkstra not optimal for this case?

algorithm,go
I am trying to solve the following problem from project euler (please take a look at description and the example in the link, but here is the short explanation). in the matrix, find the minimal path sum from the top left to the bottom right, by moving left, right, up,...

## Recursive algorithm that returns a bool when checking if array[i] == i (must be O(log n))

c++,arrays,algorithm,recursion
I'm trying to write a recursive algorithm that returns true if at least one array[i] == i. And false if there is no array[i] = i. Also, the parameters needed are (int * arr, int start, int end). So i'll be traversing the array with a pointer. For example: int...