20240605 Finished
This commit is contained in:
parent
d77d6c9f48
commit
a853d0c88b
|
@ -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;
|
||||
mod p100_same_tree;
|
||||
mod p226_invert_binary_tree;
|
61
src/problem/p226_invert_binary_tree.rs
Normal file
61
src/problem/p226_invert_binary_tree.rs
Normal 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]);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user