File tree 2 files changed +30
-1
lines changed
Lowest Common Ancestor of a Binary Search Tree
2 files changed +30
-1
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change @@ -15,6 +15,8 @@ Binary Tree Preorder Traversal
15
15
Binary Tree Postorder Traversal
16
16
Serialize and Deserialize Binary Tree
17
17
Word Break
18
- Binary Tree Paths
18
+ Binary Tree Paths
19
+ Lowest Common Ancestor of a Binary Search Tree
19
20
21
+
20
22
Until 12/2
You can’t perform that action at this time.
0 commit comments