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.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
解决思路
1. 递归:当前节点的值 与 左节点的最右子节点(左子树最大的节点)、右节点的最左子节点(右子树最小的节点) 比较;
2. 非递归中序遍历(前后指针);
方法1较方法2有较多的重复计算,方法2的时间复杂度为O(n).
程序
1. 递归
public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
long leftMax = getLeftMax(root.left);
long rightMin = getRightMin(root.right);
if (leftMax >= root.val || rightMin <= root.val) {
return false;
}
return isValidBST(root.left) && isValidBST(root.right);
}
private long getLeftMax(TreeNode root) {
if (root == null) {
return Long.MIN_VALUE;
}
TreeNode node = root;
while (node.right != null) {
node = node.right;
}
return (long)node.val;
}
private long getRightMin(TreeNode root) {
if (root == null) {
return Long.MAX_VALUE;
}
TreeNode node = root;
while (node.left != null) {
node = node.left;
}
return (long)node.val;
}
}
2. 非递归中序遍历
public class Solution {
// inorder traversal, two pointers
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> s = new Stack<>();
TreeNode node = root;
TreeNode pre = null;
while (node != null || !s.isEmpty()) {
while (node != null) {
s.push(node);
node = node.left;
}
if (!s.isEmpty()) {
TreeNode cur = s.pop();
if (pre != null && pre.val >= cur.val) {
return false;
}
pre = cur;
node = cur.right;
}
}
return true;
}
}

浙公网安备 33010602011771号