diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 172c354..4a177f6 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -49,4 +49,5 @@ mod p145_binary_tree_postorder_traversal; mod p987_vertical_order_traversal_of_a_binary_tree; mod p102_binary_tree_level_order_traversal; mod p107_binary_tree_level_order_traversal_ii; -mod p103_binary_tree_zigzag_level_order_traversal; \ No newline at end of file +mod p103_binary_tree_zigzag_level_order_traversal; +mod p105_construct_binary_tree_from_preorder_and_inorder_traversal; \ No newline at end of file diff --git a/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs new file mode 100644 index 0000000..363dd3a --- /dev/null +++ b/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs @@ -0,0 +1,87 @@ +/** + * [105] Construct Binary Tree from Preorder and Inorder Traversal + */ +pub struct Solution {} + +use surf::middleware::logger::new; + +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 build_tree(preorder: Vec, inorder: Vec) -> Option>> { + if preorder.len() == 0 { + return None; + } + + let root = Rc::new(RefCell::new( + TreeNode::new(preorder[0]))); + let mut stack = Vec::new(); + stack.push(Rc::clone(&root)); + let mut inorder_index = 0; + + for i in 1..preorder.len() { + let mut node = Rc::clone(stack.last().unwrap()); + + if node.borrow().val != inorder[inorder_index] { + let new_node = Rc::new(RefCell::new( + TreeNode::new(preorder[i]))); + stack.push(Rc::clone(&new_node)); + node.borrow_mut().left = Some(new_node); + } else { + while let Some(top) = stack.last() { + if top.borrow().val == inorder[inorder_index] { + node = Rc::clone(top); + stack.pop(); + inorder_index += 1; + } else { + break; + } + } + + let new_node = Rc::new(RefCell::new( + TreeNode::new(preorder[i]))); + stack.push(Rc::clone(&new_node)); + node.borrow_mut().right = Some(new_node); + } + } + + Some(root) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_105() { + assert_eq!(Solution::build_tree( + vec![3,9,20,15,7], + vec![9,3,15,20,7]), + to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)])); + } +}