Validate Binary Search Tree

func validBst(t *Tree) bool {
	if (t == nil) {
		return true
	}

	if (t.left  != nil && t.left.value  > t.value ||
		t.right != nil && t.right.value < t.value) {
		return false
	}

	return validBst(t.left) && validBst(t.right)
}

#Challenge

SourceLanguageRuntime
DailyBytego\(\mathcal{O}(n)\)

Given a binary tree containing unique values, assert whether the tree is a valid binary search tree.

#Solution

Recursively assert the Binary Search Tree condition on every node on the tree. I.E.

#Tree Implementation

type Tree struct {
	value int
	left, right *Tree
}

#Test Cases

#Setup

We'll be testing using the following tree structures:

            2
Tree a:   /   \
         1     3

            1
Tree b:   /   \
         2     3
tree_a := Tree{2,
	&Tree{1, nil, nil},
	&Tree{3, nil, nil},
}

tree_b := Tree{1,
	&Tree{2, nil, nil},
	&Tree{3, nil, nil},
}

#Tests

validBst(&tree_a) // true
validBst(&tree_b) // false