diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4d1cc51..ef61b66 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -141,4 +141,5 @@ mod p224_basic_calculator; mod p21_merge_two_sorted_lists; mod p104_maximum_depth_of_binary_tree; mod p100_same_tree; -mod p226_invert_binary_tree; \ No newline at end of file +mod p226_invert_binary_tree; +mod p101_symmetric_tree; \ No newline at end of file diff --git a/src/problem/p101_symmetric_tree.rs b/src/problem/p101_symmetric_tree.rs new file mode 100644 index 0000000..c2cac57 --- /dev/null +++ b/src/problem/p101_symmetric_tree.rs @@ -0,0 +1,71 @@ +/** + * [101] Symmetric 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 is_same(left: &Option>>, right: &Option>>) -> bool { + if left.is_some() ^ right.is_some() { + return false; + } + + if left.is_none() && right.is_none() { + return true; + } + + let left = left.as_ref().unwrap(); + let right = right.as_ref().unwrap(); + + if left.borrow().val != right.borrow().val { + return false; + } + + Self::is_same(&left.borrow().left, &right.borrow().right) + && Self::is_same(&left.borrow().right, &right.borrow().left) + } + + pub fn is_symmetric(root: Option>>) -> bool { + if let Some(root) = root { + return Self::is_same(&root.borrow().left, &root.borrow().right); + } + + true + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_101() { + assert!(Solution::is_symmetric(tree![1,2,2,3,4,4,3])); + assert!(!Solution::is_symmetric(tree!(1,2,2,"null",3,"null",3))) + } +}