Skip to content

Commit 257ced0

Browse files
committed
1
1 parent fb3b69b commit 257ced0

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

notes/src/day18/lc106.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,45 @@ public:
3636
};
3737
```
3838

39-
## 学习感想
39+
## 学习感想
40+
41+
```rust
42+
43+
// Definition for a binary tree node.
44+
#[derive(Debug, PartialEq, Eq)]
45+
pub struct TreeNode {
46+
pub val: i32,
47+
pub left: Option<Rc<RefCell<TreeNode>>>,
48+
pub right: Option<Rc<RefCell<TreeNode>>>,
49+
}
50+
51+
impl TreeNode {
52+
#[inline]
53+
pub fn new(val: i32) -> Self {
54+
TreeNode {
55+
val,
56+
left: None,
57+
right: None
58+
}
59+
}
60+
}
61+
use std::rc::Rc;
62+
use std::cell::RefCell;
63+
struct Solution {}
64+
impl Solution {
65+
pub fn build_tree(inorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
66+
Self::build_tree_ref(&inorder, &postorder)
67+
}
68+
69+
pub fn build_tree_ref(inorder: &[i32], postorder: &[i32]) -> Option<Rc<RefCell<TreeNode>>> {
70+
if inorder.len() == 0usize { return None }
71+
let n: usize = inorder.len();
72+
let mut num = postorder[n - 1usize];
73+
let pos: usize = inorder.iter().position(|&x| x == num).unwrap();
74+
let mut tn: TreeNode = TreeNode::new(num);
75+
tn.left = Self::build_tree_ref(&inorder[..pos], &postorder[..pos]);
76+
tn.right = Self::build_tree_ref(&inorder[pos + 1usize .. ], &postorder[pos .. n - 1usize]);
77+
Some(Rc::new(RefCell::new(tn)))
78+
}
79+
}
80+
```

0 commit comments

Comments
 (0)