20240605 Finished

This commit is contained in:
jackfiled 2024-06-05 10:56:24 +08:00
parent d77d6c9f48
commit a853d0c88b
2 changed files with 63 additions and 1 deletions

View File

@ -141,3 +141,4 @@ mod p224_basic_calculator;
mod p21_merge_two_sorted_lists; mod p21_merge_two_sorted_lists;
mod p104_maximum_depth_of_binary_tree; mod p104_maximum_depth_of_binary_tree;
mod p100_same_tree; mod p100_same_tree;
mod p226_invert_binary_tree;

View File

@ -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<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::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
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]);
}
}