diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index ddd634b4..336cc92f 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -254,7 +254,56 @@ public: Java: +```Java +class Solution { + // 递归 + TreeNode max; + public boolean isValidBST(TreeNode root) { + if (root == null) { + return true; + } + // 左 + boolean left = isValidBST(root.left); + if (!left) { + return false; + } + // 中 + if (max != null && root.val <= max.val) { + return false; + } + max = root; + // 右 + boolean right = isValidBST(root.right); + return right; + } +} +class Solution { + // 迭代 + public boolean isValidBST(TreeNode root) { + if (root == null) { + return true; + } + Stack stack = new Stack<>(); + TreeNode pre = null; + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left;// 左 + } + // 中,处理 + TreeNode pop = stack.pop(); + if (pre != null && pop.val <= pre.val) { + return false; + } + pre = pop; + + root = pop.right;// 右 + } + return true; + } +} +``` Python: