
方法1: recursion。直接按照题目给出的三个判定条件来check是否为valid bst。时间复杂nlogn(可能有错),空间复杂n。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if(root.left == null && root.right == null) return true;
boolean left = root.left != null ? isValidBST(root.left) : true;
boolean right = root.right != null ? isValidBST(root.right) : true;
if(!(left && right)) return false;
int leftBiggest = 0;
int rightSmallest = 0;
if (root.left != null) leftBiggest = leftBiggest(root.left);
if (root.right != null) rightSmallest = rightSmallest(root.right);
if(root.left == null){
if( root.val < rightSmallest) return true;
}else if(root.right == null){
if(root.val > leftBiggest ) return true;
}else{
if(root.val > leftBiggest && root.val < rightSmallest) return true;
}
return false;
}
public int leftBiggest(TreeNode root){
TreeNode copy = root;
while(copy.right != null){
copy = copy.right;
}
return copy.val;
}
public int rightSmallest(TreeNode root){
TreeNode copy = root;
while(copy.left != null){
copy = copy.left;
}
return copy.val;
}
}
总结:
- 这道题应该是很经典的一道题,lc官方解答我都没看呢,第二次做的时候一定要全部看一遍。
该博客讨论了一种使用递归方法检查二叉树是否符合有效二叉搜索树条件的算法。通过比较节点值与左右子树的最大值和最小值,确保每个节点满足BST规则。代码中定义了辅助函数来获取左子树的最大值和右子树的最小值,最后总结这是LC官方题目的一种经典解决方案。
513

被折叠的 条评论
为什么被折叠?



