Validate Binary Search Tree

https://leetcode.com/problems/validate-binary-search-tree/java

Given a binary tree, determine if it is a valid binary search tree (BST).node

Assume a BST is defined as follows:markdown

* 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.

OJ’s Binary Tree Serialization:less

The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.spa

Here’s an example:code

1
/ \
2 3
/
4
\
5排序

The above binary tree is serialized as 「{1,2,3,#,#,4,#,#,5}」.leetcode

題意:檢查一顆二叉樹是否爲二叉搜索樹。
ps:二叉查找樹(Binary Search Tree),(又:二叉搜索樹,二叉排序樹)它或者是一棵空樹,或者是具備下列性質的二叉樹: 若它的左子樹不空,則左子樹上全部結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上全部結點的值均大於它的根結點的值; 它的左、右子樹也分別爲二叉排序樹。
思路:DFS遍歷二叉樹,檢索左子樹時以父節點下限爲下限,已父節點爲上限;檢索右子樹時以父節點爲下限,以父節點上限爲上限。根節點上限下限分別爲int的上下限。
實現:get

public class Solution {

      public boolean isValidBST(TreeNode root ) {
           if (root == null)
               return true ;
           return isValidBST(root .left , Long. MIN_VALUE, root .val )
                   && isValidBST( root. right, root. val, Long.MAX_VALUE );
     }

      public boolean isValidBST(TreeNode root , long min, long max ) {
           if (root == null)
               return true ;
           if (root .val > min && root. val < max)
               return isValidBST(root .left , min , root .val )
                        && isValidBST( root. right, root .val , max );
           return false ;

     }
}
相關文章
相關標籤/搜索