码迷,mamicode.com
首页 > 其他好文 > 详细

LC.98.Validate Binary Search Tree

时间:2018-03-02 12:19:44      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:contains   blog   body   determine   pos   example   follow   bool   技术分享   

https://leetcode.com/problems/validate-binary-search-tree/description/
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 be binary search trees.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.

note: by the definition, here it mentions:
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.
time: o(n)
space: o(n)
 1 public boolean isValidBST(TreeNode root) {
 2         if (root == null ) return true;
 3         return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
 4     }
 5 
 6     private boolean helper(TreeNode root, long minValue, long maxValue) {
 7         if (root == null) return true ;
 8         if (root.val >=maxValue || root.val <= minValue){
 9             return false ;
10         }
11         return helper(root.left, minValue, root.val) && helper(root.right, root.val, maxValue);
12     }

 


技术分享图片

 




LC.98.Validate Binary Search Tree

标签:contains   blog   body   determine   pos   example   follow   bool   技术分享   

原文地址:https://www.cnblogs.com/davidnyc/p/8492027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!