-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathSolution.rs
60 lines (59 loc) · 1.49 KB
/
Solution.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// 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 {
fn reset(
inorder: &Vec<i32>,
i_left: usize,
i_right: usize,
postorder: &Vec<i32>,
p_left: usize,
p_right: usize,
) -> Option<Rc<RefCell<TreeNode>>> {
if i_left == i_right {
return None;
}
let val = postorder[p_right - 1];
let index = inorder.iter().position(|&v| v == val).unwrap();
Some(Rc::new(RefCell::new(TreeNode {
val,
left: Self::reset(
inorder,
i_left,
index,
postorder,
p_left,
p_left + index - i_left,
),
right: Self::reset(
inorder,
index + 1,
i_right,
postorder,
p_left + index - i_left,
p_right - 1,
),
})))
}
pub fn build_tree(inorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
let n = inorder.len();
Self::reset(&inorder, 0, n, &postorder, 0, n)
}
}