Skip to content

Instantly share code, notes, and snippets.

@vishesh
Last active November 28, 2015 05:04
Show Gist options
  • Select an option

  • Save vishesh/15a3e2f0f1d2404f6cce to your computer and use it in GitHub Desktop.

Select an option

Save vishesh/15a3e2f0f1d2404f6cce to your computer and use it in GitHub Desktop.
Largest BST subtree in a given Binary Tree
open Core.Std
type tree = Empty | Node of int * tree * tree
let rec largest_bst t =
let min_exn (lst:int list) : int =
Option.value_exn (List.min_elt lst ~cmp:Int.compare)
and max_exn (lst:int list) : int =
Option.value_exn (List.max_elt lst ~cmp:Int.compare)
in
match t with
| Empty -> (true, 0, Empty, Int.max_value, Int.min_value)
| Node (v, l, r) ->
let (top_r, size_r, lar_r, rmin, rmax) = largest_bst r in
let (top_l, size_l, lar_l, lmin, lmax) = largest_bst l in
let new_min = min_exn [lmin; rmin; v] in
let new_max = max_exn [rmax; lmax; v] in
let valid_left = (l = Empty) || (lmin < v && lmax < v) in
let valid_right = (r = Empty) || (rmin > v && rmax > v) in
match (top_l, top_r) with
| (true, true) when valid_right && valid_left ->
(true, size_l + size_r + 1, t, new_min, new_max)
| _ ->
if size_l > size_r then
(false, size_l, lar_l, new_min, new_max)
else
(false, size_r, lar_r, new_min, new_max)
let () =
let t1 = Node (5, Node (2, Node (1, Empty, Empty),
Node (3, Empty, Empty)),
Node (4, Empty, Empty)) in
let t2 = Node (50, Node (10, Node (5, Empty, Empty), Node (20, Empty, Empty)),
Node (60, Node (55, Node (45, Empty, Empty), Empty),
Node (70, Node (65, Empty, Empty),
Node (80, Empty, Empty)))) in
let t3 = Node (50, Node (30, Node (5, Empty, Empty), Node (20, Empty, Empty)),
Node (60, Node (45, Empty, Empty),
Node (70, Node (65, Empty, Empty),
Node (80, Empty, Empty)))) in
let (_, s1, _, _, _) = largest_bst t1 in
let (_, s2, _, _, _) = largest_bst t2 in
let (_, s3, _, _, _) = largest_bst t3 in
printf "%d\n%d\n%d\n" s1 s2 s3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment