Title:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node ' s key.
- The right subtree of a node contains only nodes with keys greater than the node ' s key.
- Both the left and right subtrees must also is binary search trees.
Test Instructions:
Given a binary tree, determine if it is a valid two-fork search tree (BST).
Suppose the binary search tree (BST) is defined as follows:
- The node value on the left subtree of the node is less than this node value.
- The node value on the right subtree of the node is greater than this node value.
- The left and right subtree must be a two-fork search tree.
Algorithm Analysis:
Reference http://www.programcreek.com/2012/12/leetcode-validate-binary-search-tree-java/
By recursive method, each node is checked separately, the values on the left subtree of the node are smaller than the node values, and the values on the subtree are greater than the node values.
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution{Public Boolean isvalidbst (TreeNode root) { return isvalidbst (Root, Double.negative_infinity, double.positive_infinity); } public boolean Isvalidbst (TreeNode p, double min, double max) { if (p==null) return true; if (p.val <= min | | p.val >= max) return false; Return Isvalidbst (p.left, Min, p.val) && Isvalidbst (P.right, P.val, max);} } </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode][java] Validate Binary Search Tree