|
| 1 | +/** |
| 2 | + * [98] Validate Binary Search Tree |
| 3 | + * |
| 4 | + * Given a binary tree, determine if it is a valid binary search tree (BST). |
| 5 | + * |
| 6 | + * Assume a BST is defined as follows: |
| 7 | + * |
| 8 | + * |
| 9 | + * The left subtree of a node contains only nodes with keys less than the node's key. |
| 10 | + * The right subtree of a node contains only nodes with keys greater than the node's key. |
| 11 | + * Both the left and right subtrees must also be binary search trees. |
| 12 | + * |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * |
| 16 | + * |
| 17 | + * Input: |
| 18 | + * 2 |
| 19 | + * / \ |
| 20 | + * 1 3 |
| 21 | + * Output: true |
| 22 | + * |
| 23 | + * |
| 24 | + * Example 2: |
| 25 | + * |
| 26 | + * |
| 27 | + * 5 |
| 28 | + * / \ |
| 29 | + * 1 4 |
| 30 | + * / \ |
| 31 | + * 3 6 |
| 32 | + * Output: false |
| 33 | + * Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value |
| 34 | + * is 5 but its right child's value is 4. |
| 35 | + * |
| 36 | + * |
| 37 | + */ |
| 38 | +pub struct Solution {} |
| 39 | + |
| 40 | +// submission codes start here |
| 41 | + |
| 42 | +// Definition for a binary tree node. |
| 43 | +use super::util::tree::{TreeNode, to_tree}; |
| 44 | + |
| 45 | +use std::rc::Rc; |
| 46 | +use std::cell::RefCell; |
| 47 | +impl Solution { |
| 48 | + pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool { |
| 49 | + let mut vec = vec![]; |
| 50 | + Solution::preorder_traverse(root.as_ref(), &mut vec) |
| 51 | + } |
| 52 | + |
| 53 | + fn preorder_traverse(root: Option<&Rc<RefCell<TreeNode>>>, formers: &mut Vec<(i32,i32)>) -> bool { |
| 54 | + if let Some(node) = root { |
| 55 | + let root_val = root.as_ref().unwrap().borrow().val; |
| 56 | + for former in formers.iter() { |
| 57 | + if (former.0 < 0 && root_val >= former.1) || |
| 58 | + (former.0 > 0 && root_val <= former.1) { |
| 59 | + return false |
| 60 | + } |
| 61 | + } |
| 62 | + let mut to_right = formers.clone(); |
| 63 | + formers.push((-1, root_val)); |
| 64 | + to_right.push((1, root_val)); |
| 65 | + Solution::preorder_traverse(node.borrow().left.as_ref(), formers) && |
| 66 | + Solution::preorder_traverse(node.borrow().right.as_ref(), &mut to_right) |
| 67 | + } else { |
| 68 | + true |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// submission codes end |
| 74 | + |
| 75 | +#[cfg(test)] |
| 76 | +mod tests { |
| 77 | + use super::*; |
| 78 | + |
| 79 | + #[test] |
| 80 | + fn test_98() { |
| 81 | + assert_eq!(Solution::is_valid_bst(tree![5,1,4,null,null,3,6]), false); |
| 82 | + assert_eq!(Solution::is_valid_bst(tree![2,1,3]), true); |
| 83 | + assert_eq!(Solution::is_valid_bst(tree![10,5,15,null,null,6,20]), false); |
| 84 | + } |
| 85 | +} |
0 commit comments