LeetCode-98-Valid-BST

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

Quesion

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:

1
2
3
4
Input:
2
/ \
1 3

Output: true

Example 2:

1
2
3
4
5
  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.

Solution

采用迭代处理

基本原理就是中序遍历过程,期间只要判断是否存在不满足条件,也就是有序

Runtime: 1 ms, faster than 36.18% of Java online submissions for Validate Binary Search Tree.
Memory Usage: 40.5 MB, less than 5.01% of Java online submissions for Validate Binary Search Tree.

1
2
3
4
5
6
7
8
9
public boolean isValidBST(TreeNode root) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean isValid(TreeNode root, Long min, Long max) {
if (root == null) return true;
if (root.val <= min || root.val >= max) return false;
return isValid(root.left, min, (long)root.val) && isValid(root.right, (long)root.val, max);
}

采用stack,非迭代

1
2


原创技术分享,您的支持将鼓励我继续创作