2020-ARTS-打卡第十四天
Algorithm 题目 题目描述 98.验证二叉搜索树,给定一个二叉树,判断其是否是一个有效的二叉搜索树。假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的树 节点的右子树只包含大于当前节点的树 所有左子树及右子树自身也必须是二叉搜索树 题目解答 import java.util.Stack; public class ValidBST { public boolean isValidBST (TreeNode root) { Stack<TreeNode> stack = new Stack<>(); double inorder = -Double.MAX_VALUE; while (!stack.isEmpty() || root != null) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if (inorder >= root.val) { return false; } inorder = root.val; root = root.right; } return true; } } 使用中序遍历(即左->根->右)来实现,从左至右进行比对,每次与上次保存的值进行对比,如果当前节点值比上次保存的值小,则可以判定此树不是二叉搜索树。时间复杂度为O(n),空间复杂度为O(n) ...