【LeetCode】98. Validate Binary Search Tree
Difficulty:Medium
More:【目录】LeetCode Java实现
Description
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:
- 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 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.
Intuition
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.
3. Method 3:
using iterative inorder traversal.
Solution
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 3
public boolean isValidBST(TreeNode root) { if(root==null) return true; Stack<TreeNode> stk = new Stack<>(); TreeNode pre = null; while(root!=null || !stk.isEmpty()){ while(root!=null){ stk.push(root); root=root.left; } TreeNode cur = stk.peek(); if(pre!=null && pre.val>=cur.val) return false; root=stk.pop().right; pre = cur; } return true; }
Complexity
Method 1:
Time complexity : O(nlogn)
Space complexity : O(n)
Method 2:
Time complexity : O(n)
Space complexity : O(n)
Method 3:
Time complexity : O(n)
Space complexity : O(logn) depth of the tree
More:【目录】LeetCode Java实现