Merge pull request #1785 from fwqaaq/patch-5

Update 0098.验证二叉搜索树.md about rust
This commit is contained in:
程序员Carl
2022-12-17 11:43:52 +08:00
committed by GitHub

View File

@ -637,6 +637,55 @@ object Solution {
}
```
## rust
递归:
```rust
impl Solution {
pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
Self::valid_bst(i64::MIN, i64::MAX, root)
}
pub fn valid_bst(low: i64, upper: i64, root: Option<Rc<RefCell<TreeNode>>>) -> 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())
}
}
```
辅助数组:
```rust
impl Solution {
pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> 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<Rc<RefCell<TreeNode>>>, mut v: &mut Vec<i64>) {
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);
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>