To watch the youtube video on this topic where I explain everything, please click here.
This series of problems asks to find the "lowest common ancestor" for two types of binary trees.
A "common ancestor" for two nodes is a node that has those two nodes as descendants (and a node can be a descendants of itself).
The "lowest" common ancestor is the node that's closest to the two nodes that satisfies the common ancestor condition.
[Easy] Find Lowest Common Ancestor In Binary Search Tree
Given the root of a binary search tree and two nodes in the tree, p and q, find the lowest common ancestor of p and q. (Problem on Leetcode.)
For example, in the following diagram if p is node 3 and q is node 1, then the LCA(p,q) is node 2.
We'll recognize that the node that's the LCA node of p and q must be one of the following:
For this solution, we'll take advantage of the "search" property of Binary Search Trees. In a BST, a node's left children have values that are less than the node's value, and the node's right children have values that are greater than the node's value. Because of this, we'll know if the p is on the left and q is on the right without having to search those subtrees.
The C++ solution to the problem is as follows:
The time complexity is O(N). (Specifically O(H) where H is the height of the tree.)
The space complexity is O(1) because we're not using any extra space.
Note: We choose the iterative solution here because the recursive solution has a space complexity of O(N). However, he code itself is basically the same as the iterative approach.
[Medium] Find Lowest Common Ancestor In Binary Tree
Given the root of a binary tree and two nodes in the tree, p and q, find the lowest common ancestor of p and q. (Problem on Leetcode.)
For example, in the following diagram if p is node 2 and q is node 9, then the LCA(p,q) is node 7.
Like the previous solution, we'll recognize that the node that's the LCA node of p and q must be one of the following:
However, this time we have a regular binary tree, and so we're forced to look through the entire tree until we find p and q. Our strategy is, for each node, recursively check the left and right subtrees to determine if either subtree has p or q in it. The node that satisfies one of these conditions is the lowest common ancestor.
The time complexity is O(N), because our recursion visits each node exactly once.
The space complexity is O(N) because we potentially hold the entire tree in memory at the same time.
Note: We choose the recursive solution here because the code/algorithm is simpler. The iterative solution's code is harder and requires a stack.
Hi, I'm srcmake. I play video games and develop software.
Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
License: All code and instructions are provided under the MIT License.