98. Validate Binary Search Tree
https://leetcode.com/problems/validate-binary-search-tree/description/
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.
Thoughts
检验给定BST是否合法。BST进行中序遍历一定是升序的,利用此性质检查当前结点值是否>上个结点。
Code
class Solution {
TreeNode prev = null;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (!isValidBST(root.left) || prev != null && prev.val >= root.val) {
return false;
}
prev = root;
return isValidBST(root.right);
}
}
Analysis
做题耗时 5min
时间复杂度同中序遍历,O(n)
Ver.2
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void pushLeft(Stack<TreeNode> stack, TreeNode node) {
while (node != null) {
stack.push(node);
node = node.left;
}
}
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
pushLeft(stack, root);
TreeNode pre = null;
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (pre != null && pre.val >= node.val) {
return false;
}
pre = node;
pushLeft(stack, node.right);
}
return true;
}
}
Last updated
Was this helpful?