Skip to content

Commit 7067cec

Browse files
committed
Lowest Common Ancestor of a Binary Search Tree
1 parent 44f17ff commit 7067cec

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode
3+
# attr_accessor :val, :left, :right
4+
# def initialize(val)
5+
# @val = val
6+
# @left, @right = nil, nil
7+
# end
8+
# end
9+
10+
# @param {TreeNode} root
11+
# @param {TreeNode} p
12+
# @param {TreeNode} q
13+
# @return {TreeNode}
14+
def lowest_common_ancestor(root, p, q)
15+
return root if root.nil?
16+
17+
18+
if root.val > p.val && root.val > q.val
19+
return lowest_common_ancestor(root.left, p, q)
20+
end
21+
22+
if root.val < p.val && root.val < q.val
23+
return lowest_common_ancestor(root.right, p, q)
24+
end
25+
26+
return root
27+
end

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ Binary Tree Preorder Traversal
1515
Binary Tree Postorder Traversal
1616
Serialize and Deserialize Binary Tree
1717
Word Break
18-
Binary Tree Paths
18+
Binary Tree Paths
19+
Lowest Common Ancestor of a Binary Search Tree
1920

21+
2022
Until 12/2

0 commit comments

Comments
 (0)