diff --git a/src/problem/mod.rs b/src/problem/mod.rs index ef61b66..2ee46c9 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -142,4 +142,5 @@ mod p21_merge_two_sorted_lists; mod p104_maximum_depth_of_binary_tree; mod p100_same_tree; mod p226_invert_binary_tree; -mod p101_symmetric_tree; \ No newline at end of file +mod p101_symmetric_tree; +mod p114_flatten_binary_tree_to_linked_list; \ No newline at end of file diff --git a/src/problem/p114_flatten_binary_tree_to_linked_list.rs b/src/problem/p114_flatten_binary_tree_to_linked_list.rs new file mode 100644 index 0000000..1251afa --- /dev/null +++ b/src/problem/p114_flatten_binary_tree_to_linked_list.rs @@ -0,0 +1,77 @@ +/** + * [114] Flatten Binary Tree to Linked List + */ +pub struct Solution {} + +use crate::util::tree::{to_tree, TreeNode}; + +// 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::cell::RefCell; +use std::rc::Rc; +impl Solution { + fn flatten_tree(root: &Rc>) -> Rc> { + if (root.borrow().left.is_none() && root.borrow().right.is_none()) { + // 只有一个节点 + return Rc::clone(root); + } + + if root.borrow().right.is_some() { + let right = Rc::clone(&root.borrow().right.as_ref().unwrap()); + + if root.borrow().left.is_some() { + let left = Rc::clone(&root.borrow().left.as_ref().unwrap()); + root.borrow_mut().right = Some(Rc::clone(&left)); + root.borrow_mut().left = None; + + let right_right = Self::flatten_tree(&left); + right_right.borrow_mut().right = Some(Rc::clone(&right)); + + return Self::flatten_tree(&right); + } else { + return Self::flatten_tree(&right); + } + } else { + let left = Rc::clone(&root.borrow().left.as_ref().unwrap()); + + root.borrow_mut().right = Some(Rc::clone(&left)); + root.borrow_mut().left = None; + + return Self::flatten_tree(&left); + } + } + + pub fn flatten(root: &mut Option>>) { + if let Some(root) = root { + Self::flatten_tree(root); + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_114() {} +}