From c6c9d5170446f9f336b2f3a495bebebbe15abe03 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 19 Jun 2024 11:05:38 +0800 Subject: [PATCH] 20240619 Finished --- src/problem/mod.rs | 3 +- .../p98_validate_binary_search_tree.rs | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 src/problem/p98_validate_binary_search_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6dec650..ee4c0f9 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -152,4 +152,5 @@ mod p222_count_complete_tree_nodes; mod p199_binary_tree_right_side_view; mod p637_average_of_levels_in_binary_tree; mod p530_minimum_absolute_difference_in_bst; -mod p230_kth_smallest_element_in_a_bst; \ No newline at end of file +mod p230_kth_smallest_element_in_a_bst; +mod p98_validate_binary_search_tree; \ No newline at end of file diff --git a/src/problem/p98_validate_binary_search_tree.rs b/src/problem/p98_validate_binary_search_tree.rs new file mode 100644 index 0000000..e86b398 --- /dev/null +++ b/src/problem/p98_validate_binary_search_tree.rs @@ -0,0 +1,67 @@ +/** + * [98] Validate Binary Search Tree + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn inorder_iterate(node: &Rc>, array: &mut Vec) { + if let Some(left) = node.borrow().left.as_ref() { + Self::inorder_iterate(left, array); + } + array.push(node.borrow().val); + if let Some(right) = node.borrow().right.as_ref() { + Self::inorder_iterate(right, array); + } + } + + pub fn is_valid_bst(root: Option>>) -> bool { + let mut array = vec![]; + + if let Some(root) = root { + Self::inorder_iterate(&root, &mut array); + } + + for i in 1..array.len() { + if array[i - 1] >= array[i] { + return false; + } + } + + true + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_98() { + } +}