zangdaiyang 2019-10-28
More:【目录】LeetCode Java实现
https://leetcode.com/problems/validate-binary-search-tree/
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
Example 1:
2 / 1 3 Input: [2,1,3] Output: true
Example 2:
5 / 1 4 / 3 6 Input: [5,1,4,null,null,3,6] Output: false Explanation: The root node‘s value is 5 but its right child‘s value is 4.
1.Method 1:
* Determine if left subtree and right subtree are valid binary search trees
* Compare root.val with maxValue in left subtree and minValue in right subtree;
2.Method 2:
* give the maxium range {max, min} for root.val
* update the {max, min} for subtree‘s root.
Method 1
public boolean isValidBST(TreeNode root) { if(root==null ) return true; TreeNode left = root.left, right=root.right; if(!isValidBST(left) || !isValidBST(right)) return false; // find the maxNode in left subtree if(left!=null) while(left.right!=null) left=left.right; // find the minNode in right subtree if(right!=null) while(right.left!=null) right=right.left; return (left==null || left.val<root.val) &&(right==null || right.val>root.val); }
Method 2
public boolean isValidBST(TreeNode root) { return helper(root, (long)Integer.MIN_VALUE-1, (long)Integer.MAX_VALUE+1); } private boolean helper(TreeNode node, long min, long max){ if(node == null) return true; return (node.val < max && node.val>min) && helper(node.left, min, node.val) && helper(node.right, node.val, max); }
Method 1:
Time complexity : O(nlogn)
Space complexity : O(n)
Method 2:
Time complexity : O(n)
Space complexity : O(n)
More:【目录】LeetCode Java实现