leetcode98 - Validate Binary Search Tree - medium
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:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.
法1.O(n) O(h) 利用性质:左边所有节点的值要比当前节点小,右边所有节点的值要比当前节点大。
那么就有想法,你每遍历到一个节点就对孩子们可取范围多加了一层限制。
递归函数头为:private boolean validateRange(TreeNode root, Integer minVal, Integer maxVal)
细节:
1.用Integer的包装类型的原因是,使用null代表无限制,你可以取无穷大。比如root的右边应该是(root.val, 无穷)的。
2.递归的时候需要根据当前根节点更新左右子树的范围。
法2.O(n) O(h) 利用性质:中序遍历是递增序列。(注意需要在左<中<右的条件下可以用这个检验。如果是左<=中<右,20- 20(root)和20(root) - 20两个中序遍历都是20,20,但前者是BST后者不是BST。)
实现1:分治法,验证合法范围。O(n), O(h)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isValidBST(TreeNode root) { return validateRange(root, null, null); } private boolean validateRange(TreeNode root, Integer minVal, Integer maxVal) { if (root == null) return true; if (minVal != null && root.val <= minVal) return false; if (maxVal != null && root.val >= maxVal) return false; return validateRange(root.left, minVal, root.val) && validateRange(root.right, root.val, maxVal); } }
实现2:recursive版中序遍历 O(n), O(h)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isValidBST(TreeNode root) { List<Integer> list = new ArrayList<>(); getInOrderResult(root, list); for (int i = 1; i < list.size(); i++) { if (list.get(i) <= list.get(i - 1)) { return false; } } return true; } private void getInOrderResult(TreeNode root, List<Integer> list) { if (root == null) { return; } getInOrderResult(root.left, list); list.add(root.val); getInOrderResult(root.right, list); } }
实现3:iterative版中序遍历 O(n), O(h)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isValidBST(TreeNode root) { // P1: null 是BST。 List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode crt = root; while (!stack.isEmpty() || crt != null) { while (crt != null) { stack.push(crt); crt = crt.left; } crt = stack.pop(); list.add(crt.val); // P2: 不管crt.right是不是null都要赋值。 crt = crt.right; } for (int i = 1; i < list.size(); i++) { if (list.get(i) <= list.get(i - 1)) { return false; } } return true; } }