The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. ― Donald E. Knuth

Algorithms

Tree

Problem :-
Find the Least Common Ancestor ( LCA ) of two nodes in a Binary Tree .
LCA of two nodes x and y in a Binary Tree is the lowest node in the tree which contain both x and y as descendants. For the Binary Tree shown below, LCA of nodes LCA of nodes 2 and 20 is 15 .
Similarly, LCA of nodes 5 and 30 is 25 .

Solution :-
Suppose we want to find the LCA of two nodes x and y.
We have seen previously how LCA in Binary Search Tree ( BST ) is computed utilizing the properties of BST but a normal binary tree may not follow those properties. So, the technique is different here.
Since our intent is to find the lowest node which is the ancestor of nodes x and y, we will starting searching that node from bottom to up in the tree. For each node starting from the bottom-most level, we will check recursively if we can find a node P suct that x lies in left subtree of P and y lies in right subtree or x in right and y in left subtree. See the implementation below.