Skip to content

Commit 42bbc7a

Browse files
committed
solve #106
1 parent 6221cdf commit 42bbc7a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,4 @@ mod n0102_binary_tree_level_order_traversal;
106106
mod n0103_binary_tree_zigzag_level_order_traversal;
107107
mod n0104_maximum_depth_of_binary_tree;
108108
mod n0105_construct_binary_tree_from_preorder_and_inorder_traversal;
109+
mod n0106_construct_binary_tree_from_inorder_and_postorder_traversal;
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)