From bb8e7312b64b13f98ca6c6ae88260a4f57375acd Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 25 Apr 2023 03:25:45 -0400 Subject: [PATCH] =?UTF-8?q?Update=200098.=E9=AA=8C=E8=AF=81=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增java 統一迭代法的寫法 有通過. AC --- problems/0098.验证二叉搜索树.md | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 95afe680..ccb63305 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -259,6 +259,36 @@ public: ## Java +```Java +//使用統一迭代法 +class Solution { + public boolean isValidBST(TreeNode root) { + Stack stack = new Stack<>(); + TreeNode pre = null; + if(root != null) + stack.add(root); + while(!stack.isEmpty()){ + TreeNode curr = stack.peek(); + if(curr != null){ + stack.pop(); + if(curr.right != null) + stack.add(curr.right); + stack.add(curr); + stack.add(null); + if(curr.left != null) + stack.add(curr.left); + }else{ + stack.pop(); + TreeNode temp = stack.pop(); + if(pre != null && pre.val >= temp.val) + return false; + pre = temp; + } + } + return true; + } +} +``` ```Java class Solution { // 递归