From ca606b7be82e94fb05653b089fa9132a43920652 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Fri, 10 Jun 2022 13:58:11 +0100 Subject: [PATCH] validate-binary-search-tree --- validate-binary-search-tree/sol.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 validate-binary-search-tree/sol.go diff --git a/validate-binary-search-tree/sol.go b/validate-binary-search-tree/sol.go new file mode 100644 index 0000000..d8cb80a --- /dev/null +++ b/validate-binary-search-tree/sol.go @@ -0,0 +1,28 @@ +package main + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isValidSubBST(root *TreeNode, min, max int) bool { + if root == nil { + return true + } + if root.Val < min || root.Val > max { + return false + } + return isValidSubBST(root.Left, min, root.Val-1) && isValidSubBST(root.Right, root.Val+1, max) +} +func isValidBST(root *TreeNode) bool { + return isValidSubBST(root, -1<<31, 1<<31) +}