|
| 1 | +/** |
| 2 | + * [106] Construct Binary Tree from Inorder and Postorder Traversal |
| 3 | + * |
| 4 | + * Given inorder and postorder traversal of a tree, construct the binary tree. |
| 5 | + * |
| 6 | + * Note:<br /> |
| 7 | + * You may assume that duplicates do not exist in the tree. |
| 8 | + * |
| 9 | + * For example, given |
| 10 | + * |
| 11 | + * |
| 12 | + * inorder = [9,3,15,20,7] |
| 13 | + * postorder = [9,15,7,20,3] |
| 14 | + * |
| 15 | + * Return the following binary tree: |
| 16 | + * |
| 17 | + * |
| 18 | + * 3 |
| 19 | + * / \ |
| 20 | + * 9 20 |
| 21 | + * / \ |
| 22 | + * 15 7 |
| 23 | + * |
| 24 | + * |
| 25 | + */ |
| 26 | +pub struct Solution {} |
| 27 | +use super::util::tree::{TreeNode, to_tree}; |
| 28 | + |
| 29 | +// submission codes start here |
| 30 | + |
| 31 | +use std::rc::Rc; |
| 32 | +use std::cell::RefCell; |
| 33 | +impl Solution { |
| 34 | + pub fn build_tree(inorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { |
| 35 | + Solution::build_tree_helper(&postorder[..], &inorder[..], ) |
| 36 | + } |
| 37 | + |
| 38 | + fn build_tree_helper(postorder: &[i32], inorder: &[i32]) -> Option<Rc<RefCell<TreeNode>>> { |
| 39 | + if postorder.is_empty() { return None } |
| 40 | + let root_idx = inorder.iter().position(|v| v == postorder.last().unwrap()).unwrap(); |
| 41 | + Some(Rc::new(RefCell::new(TreeNode{ |
| 42 | + val: *postorder.last().unwrap(), |
| 43 | + left: Solution::build_tree_helper(&postorder[0..root_idx], &inorder[0..root_idx]), |
| 44 | + right: Solution::build_tree_helper(&postorder[root_idx..postorder.len()-1], &inorder[root_idx+1..]), |
| 45 | + }))) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// submission codes end |
| 50 | + |
| 51 | +#[cfg(test)] |
| 52 | +mod tests { |
| 53 | + use super::*; |
| 54 | + |
| 55 | + #[test] |
| 56 | + fn test_106() { |
| 57 | + assert_eq!(Solution::build_tree(vec![9,3,15,20,7], vec![9,15,7,20,3]), tree![3,9,20,null,null,15,7]); |
| 58 | + assert_eq!(Solution::build_tree(vec![3,20,7], vec![7,20,3]), tree![3,null,20,null,7]); |
| 59 | + assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); |
| 60 | + } |
| 61 | +} |
0 commit comments