-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_valid_bst.rs
More file actions
44 lines (40 loc) · 1.19 KB
/
is_valid_bst.rs
File metadata and controls
44 lines (40 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;
struct Solution;
impl Solution {
pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
fn check(root: &Option<Rc<RefCell<TreeNode>>>) -> (i32, bool, i32) {
let val = root.clone().unwrap().borrow().val;
let left = root.clone().unwrap().borrow().left.clone();
let right = root.clone().unwrap().borrow().right.clone();
if left.is_some() && right.is_some() {
let (lmn, lans, lmx) = check(&left);
let (rmn, rans, rmx) = check(&right);
if lmx<val && rmn>val {
return (lmn.min(rmn), true, lmx.min(rmx));
} else {
return (lmn.min(rmn), false, lmx.min(rmx));
}
}
(val, true, val)
}
check(&root).1
}
}
fn main() {}