Validate BST

Prompt

Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing whether the BST is valid.
Each BST node has an integer value , a left child node, and a right child node. A node is said to be a valid BST node if and only if it satises the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid BST nodes themselves or None / null .
A BST is valid if and only if all of its nodes are valid BST nodes.

Sample Input

在这里插入图片描述

Sample Output

true

Solution

import java.util.*;

class Program {
	// O(n) time | O(d) space
  public static boolean validateBst(BST tree) {
    // Write your code here.
    return validateBST(tree, Integer.MAX_VALUE, Integer.MIN_VALUE);
  }
	
	public static boolean validateBST(BST tree, int maxValue, int minValue) {
		if(tree.value >= maxValue || tree.value < minValue) {
			return false;
		}
		if (tree.left != null && !validateBST(tree.left, tree.value, minValue)) {// A
			return false;
		}
		
		if(tree.right != null && !validateBST(tree.right, maxValue, tree.value)) {
			return false ;
		}
		return true;//B
		
	// 	if(tree.right != null) {
	// 		return validateBST(tree.right, maxValue, tree.value);
	// 	}
	// 	return true;
	}

  static class BST {
    public int value;
    public BST left;
    public BST right;

    public BST(int value) {
      this.value = value;
    }
  }
}

# 1A

return后,要考虑接受return的值,这是一种接受return值的方式

# 1B

如果没有三个if的情况,就一直pass,直到return tree

Solution 2

import java.util.*;

class Program {
	// O(n) time | O(d) space
  public static boolean validateBst(BST tree) {
    // Write your code here.
    return validateBST(tree, Integer.MAX_VALUE, Integer.MIN_VALUE);
  }
	
	public static boolean validateBST(BST tree, int maxValue, int minValue) {
		if (tree == null) {//A
			return true;
		}
		if(tree.value >= maxValue || tree.value < minValue) {
			return false;
		}
		return validateBST(tree.left, tree.value, minValue) && validateBST(tree.right, maxValue, tree.value);//B
	}

  static class BST {
    public int value;
    public BST left;
    public BST right;

    public BST(int value) {
      this.value = value;
    }
  }
}

# 1B

base case

# 2B

细品

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值