diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 82e736b..4d1cc51 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -140,4 +140,5 @@ mod p150_evaluate_reverse_polish_notation; mod p224_basic_calculator; mod p21_merge_two_sorted_lists; mod p104_maximum_depth_of_binary_tree; -mod p100_same_tree; \ No newline at end of file +mod p100_same_tree; +mod p226_invert_binary_tree; \ No newline at end of file diff --git a/src/problem/p226_invert_binary_tree.rs b/src/problem/p226_invert_binary_tree.rs new file mode 100644 index 0000000..fab6b4f --- /dev/null +++ b/src/problem/p226_invert_binary_tree.rs @@ -0,0 +1,61 @@ +/** + * [226] Invert Binary 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 { + pub fn invert_tree(root: Option>>) -> Option>> { + match root { + None => None, + Some(root) => { + let left = Self::invert_tree( + root.borrow_mut().left.take() + ); + let right = Self::invert_tree( + root.borrow_mut().right.take() + ); + + root.borrow_mut().left = right; + root.borrow_mut().right = left; + + Some(root) + } + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_226() { + Solution::invert_tree(tree![2, 1, 3]); + } +}