From 31ec97a8609b61a61ce1a76231493759f1e03975 Mon Sep 17 00:00:00 2001 From: Hao Xiang Date: Thu, 22 Feb 2024 09:45:09 +0800 Subject: [PATCH] 2024-02-22 --- src/tree/traversal/no_class.rs | 75 +++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/src/tree/traversal/no_class.rs b/src/tree/traversal/no_class.rs index fef68c4..74cec02 100644 --- a/src/tree/traversal/no_class.rs +++ b/src/tree/traversal/no_class.rs @@ -24,8 +24,8 @@ pub fn build_tree(preorder: Vec, inorder: Vec) -> Option, postorder: Vec) -> Option, + postorder: Vec, +) -> Option>> { + fn build(preorder: &[i32], postorder: &[i32]) -> Option>> { + if preorder.is_empty() { + return None; + } + let root_val = preorder[0]; + let mut root = TreeNode::new(root_val); + + if preorder.len() == 1 { + return Some(Rc::new(RefCell::new(root))); + } + if preorder.len() == 2 { + let left_val = preorder[1]; + let left = TreeNode::new(left_val); + root.left = Some(Rc::new(RefCell::new(left))); + return Some(Rc::new(RefCell::new(root))); + } + + let left_val = preorder[1]; + let left_idx_in_postorder = postorder.iter().position(|&x| x == left_val).unwrap(); + + let right_val = postorder[postorder.len() - 2]; + // check + if right_val != left_val { + let right_idx_in_preorder = preorder.iter().position(|&x| x == right_val).unwrap(); + + root.left = build( + &preorder[1..right_idx_in_preorder], + &postorder[..left_idx_in_postorder + 1], + ); + root.right = build( + &preorder[right_idx_in_preorder..], + &postorder[left_idx_in_postorder + 1..postorder.len() - 1], + ); + } else { + root.left = build(&preorder[1..], &postorder[..postorder.len() - 1]); + } + + Some(Rc::new(RefCell::new(root))) + } + build(&preorder, &postorder) +} + #[cfg(test)] mod tests { use macros::tree; @@ -87,4 +142,20 @@ mod tests { tree!({3, left: {9}, right:{20, left: {15}, right:{7} }}) ); } + + #[test] + fn test_build_tree3() { + let preorder = vec![1, 2, 4, 5, 3, 6, 7]; + let postorder = vec![4, 5, 2, 6, 7, 3, 1]; + let root = construct_from_pre_post(preorder, postorder); + assert_eq!( + root, + tree!({1, left: {2, left: {4}, right:{5}}, right:{3, left: {6}, right:{7} }}) + ); + + let preorder = vec![4, 2, 1, 3]; + let postorder = vec![3, 1, 2, 4]; + let root = construct_from_pre_post(preorder, postorder); + assert_eq!(root, tree!({4, left: {2, left: {1, left: {3}}}})); + } }