~/coding-interview/find-first-common-ancestor-two-nodes-binary-tree.md

How to calculate First Common Ancestor of two Nodes in Binary Tree

2 min readAugust 14, 2020by Gorav Singal#cracking-the-coding-interview#coding-problems#algorithm
// TL;DR

Recurse on both subtrees — if one node is found in the left subtree and the other in the right, the current node is the LCA. If both are on the same side, recurse deeper into that side.

How to calculate First Common Ancestor of two Nodes in Binary Tree

First try to understand question.

  • Its a binary tree, not a binary search tree
  • Find first common ancestor
  • There is no link to parent nodes

Initial Thoughts

  • First, you can search in the tree, whether these two nodes exists in the tree.
  • Proceed only when we found both nodes in the tree
  • You can find the location of these two nodes on the tree. There can be three possibilities:
    1. If either element is the actual root, then root is the answer
    2. Both nodes found on the left OR right side of the root node (same side of root)
    3. One is on left, other is on right. Roor is the answer.

For Case-2, on finding that both nodes are on the same side. We will repeat our same algorithm going forward in that side only.

Lets see a code for this.

public class CommonAncestor {
	public static class Node {
		public int data;
		public Node left;
		public Node right;
		public Node(int data) {
			this.data = data;
			this.left = null;
			this.right = null;
		}
	}
	
	/**
	 * To check whether a node exists in a root element
	 */
	private boolean covers(Node root, Node toSearch) {
		if (root == null || toSearch == null) {
			return false;
		}
		if (root.data == toSearch.data) {
			return true;
		}
		
		return this.covers(root.left, toSearch) || this.covers(root.right, toSearch);
	}
	
	private Node helper1(Node root, Node node1, Node node2) {
		if (root == null) {
			return null;
		}
		if (root.data == node1.data || root.data == node2.data) {
			return root;
		}
		
		boolean firstNodeFoundOnLeft = this.covers(root.left, node1);
		boolean firstNodeFoundOnRight = this.covers(root.left, node2);
		
		if (firstNodeFoundOnLeft != firstNodeFoundOnRight) {
			//both are on different sides. Found result.
			return root;
		}
		
		//both are on the same side.
		return this.helper1(firstNodeFoundOnLeft ? root.left : root.right, 
				node1, node2);
	}
	
	public Node findCommonAncestor_1(Node root, Node node1, Node node2) {
		if (!this.covers(root, node1) || !this.covers(root, node2)) {
			//one or both nodes are not in the tree
			System.out.println("Not covered");
			return null;
		}
		
		return this.helper1(root, node1, node2);
	}
}

Code Explanation

  • First we check whether our tree covers both the nodes or not. If not, we do not need to go further.
  • Then, code starts with helper1(root, node1, node2)
  • Some conditions, if our root is null. No need to go further. And, if root element becomes equal to any of our search nodes. This is the result.
  • We search for both nodes, on the left side of the root node.
  • If both are on different sides. Root is the answer
  • Else, we will branch on the side (left or right), where both found.

The function calls recursively, and same code repeats.

Complexity of this code

Consider the tree to be balanced tree.

  • Initially covers() is called twice. So, its 2 times O(n), which computes to O(n)
  • Our helper1() function gets called on branches one time for each node. 2 * n/2 for both nodes. Which comes out to be: 2n/2 + 2n/4 + 2n/8 ~= O(logn)

Total complexity of this code is O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Determine if a string has all unique characters

Determine if a string has all unique characters

Problem Implement an algorithm to determine if a string has all the characters…

How to calculate angle between hour and minute hand, given a time

How to calculate angle between hour and minute hand, given a time

This problem is a simple mathematical calculation. Lets start deriving some…

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…