递归解法一
public class Solution { // 存放中序遍历结果,二分搜索树中序遍历的结果是从小往大排序的 List<Integer> list = new ArrayList<>(); public boolean isValidBST(TreeNode root) { if (root!= null) { isValidBST(root.left); list.add(root.val); isValidBST(root.right); } // 注意要小于等于,搜索树里不能有相同元素 for (int i = 1; i < list.size(); i++) { if (list.get(i - 1) >= list.get(i)) return false; } return true; }}
递归解法二,代码结构更清晰
class Solution { private ArrayList<Integer> tempList = new ArrayList<>(); public boolean isValidBST(TreeNode root) { preOrder(root); for (int i = 1; i < tempList.size(); i++) { if (tempList.get(i - 1) >= tempList.get(i)) return false; } return true; } public void preOrder(TreeNode node) { if (node != null) { preOrder(node.left); tempList.add(node.val); preOrder(node.right); } }}