题目如下:
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.
二叉搜索树一个最重要的特点就是先序遍历的结果是升序。所以判断一颗二叉搜索树是否合法的,可以判断先序遍历的结果是否为升序的,因此需要有O(n)的空间复杂度来记录先序遍历的结果。一个改进就是,每当遍历一个节点时,记住它的前驱节点即可,比较自身和前驱,不过自身比前驱大,则正确,如果小,就不是合法的。第一个值是没有前驱的,需要用一个变量来标记是否是第一个节点。此时空间复杂度就为O(1)了。
代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
boolean first = true;
int[] pre = new int[1];
public boolean isValidBST(TreeNode root) {
return isValid(root);
}
private boolean isValid(TreeNode node){
if(node == null) return true;
boolean flag1 = isValid(node.left);
boolean flag2 = false;
if(flag1 & first){
first = !first;
pre[0] = node.val;
flag2 = true;
}else if(flag1){
if(node.val > pre[0]){
flag2 = true;
pre[0] = node.val;
}
}
if(flag1 & flag2){
return isValid(node.right);
}
return false;
}
}