From 8d04e8a3804b1dd7538104cb9953451109256976 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 28 Nov 2022 17:08:58 +0800 Subject: [PATCH 1/2] =?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 --- problems/0098.验证二叉搜索树.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index bb38ae35..262ad18c 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -639,6 +639,29 @@ object Solution { } ``` +## rust + +递归: + +```rust +impl Solution { + pub fn is_valid_bst(root: Option>>) -> bool { + Self::valid_bst(i64::MIN, i64::MAX, root) + } + pub fn valid_bst(low: i64, upper: i64, root: Option>>) -> bool { + if root.is_none() { + return true; + } + let root = root.as_ref().unwrap().borrow(); + if root.val as i64 <= low || root.val as i64 >= upper { + return false; + } + Self::valid_bst(low, root.val as i64, root.left.clone()) + && Self::valid_bst(root.val as i64, upper, root.right.clone()) + } +} +``` +

From c230c2d871b2b9a93fbc137b17fb5ef8b1eea48a Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 28 Nov 2022 17:23:00 +0800 Subject: [PATCH 2/2] =?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 --- problems/0098.验证二叉搜索树.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 262ad18c..a925e36a 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -662,6 +662,32 @@ impl Solution { } ``` +辅助数组: + +```rust +impl Solution { + pub fn is_valid_bst(root: Option>>) -> bool { + let mut vec = vec![]; + Self::valid_bst(root, &mut vec); + for i in 1..vec.len() { + if vec[i] <= vec[i - 1] { + return false; + } + } + true + } + pub fn valid_bst(root: Option>>, mut v: &mut Vec) { + if root.is_none() { + return; + } + let node = root.as_ref().unwrap().borrow(); + Self::valid_bst(node.left.clone(), v); + v.push(node.val as i64); + Self::valid_bst(node.right.clone(), v); + } +} +``` +