Skip to content

Commit 16f5dd8

Browse files
committed
Common Ancestor
1 parent 77139e7 commit 16f5dd8

File tree

3 files changed

+66
-8
lines changed

3 files changed

+66
-8
lines changed

LowestCommonAncestorOfBinaryTree.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Given a binary tree, find the lowest common ancestor of two given nodes in the tree.
3+
*
4+
*
5+
* _______3______
6+
* / \
7+
* ___5__ ___1__
8+
* / \ / \
9+
* 6 _2 0 8
10+
* / \
11+
* 7 4
12+
* If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous
13+
* post: Lowest Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here. Using the tree
14+
* above as an example, the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.
15+
*
16+
* Hint:
17+
* Top-down or bottom-up? Consider both approaches and see which one is more efficient.
18+
*/
19+
public class LowestCommonAncestorOfBinaryTree {
20+
public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
21+
if (root == null)
22+
return null;
23+
if (root == p || root == q)
24+
return root;
25+
TreeNode left = LCA(root.left, p, q);
26+
TreeNode right = LCA(root.right, p, q);
27+
if (left != null && right != null)
28+
return root;
29+
return left != null ? left : right;
30+
}
31+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Lowest Common Ancestor of a Binary Search Tree (BST)
3+
*
4+
* Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.
5+
*
6+
*
7+
* _______6______
8+
* / \
9+
* ___2__ ___8__
10+
* / \ / \
11+
* 0 _4 7 9
12+
* / \
13+
* 3 5
14+
* Using the above tree as an example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6.
15+
* But how about LCA of nodes 2 and 4? Should it be 6 or 2?
16+
*
17+
* According to the definition of LCA on Wikipedia: ¡°The lowest common ancestor is defined between
18+
* two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a
19+
* node to be a descendant of itself).¡± Since a node can be a descendant of itself, the LCA of 2 and
20+
* 4 should be 2, according to this definition.
21+
*
22+
* Hint:
23+
* A top-down walk from the root of the tree is enough.
24+
*/
25+
public class LowestCommonAncestorOfaBinarySearchTree {
26+
public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
27+
if (root == null || p == null || q == null)
28+
return null;
29+
if (Math.max(p.val, q.val) < root.val)
30+
return LCA(root.left, p, q);
31+
if (Math.min(p.val, q.val) > root.val)
32+
return LCA(root.right, p, q);
33+
return root;
34+
}
35+
}

LowestCommonAncestorofaBinaryTree.c

Lines changed: 0 additions & 8 deletions
This file was deleted.

0 commit comments

Comments
 (0)