-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNYBBNL.rs
67 lines (59 loc) · 1.79 KB
/
NYBBNL.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
61
62
63
64
65
66
67
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
// 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::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn increasing_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
if root.is_none() {
return None;
}
let (ans, _) = Self::f(root);
ans
}
// 返回头部和尾部
fn f(
root: Option<Rc<RefCell<TreeNode>>>,
) -> (Option<Rc<RefCell<TreeNode>>>, Option<Rc<RefCell<TreeNode>>>) {
let root = root.unwrap();
let left = root.borrow_mut().left.take();
let right = root.borrow_mut().right.take();
match (left, right) {
(Some(l), Some(r)) => {
let (n1, m1) = Self::f(Some(l));
let (n2, m2) = Self::f(Some(r));
m1.clone().unwrap().borrow_mut().right = Some(root.clone());
root.borrow_mut().right = n2;
(n1, m2)
}
(Some(l), None) => {
let (n, m) = Self::f(Some(l));
m.clone().unwrap().borrow_mut().right = Some(root.clone());
(n, Some(root.clone()))
}
(None, Some(r)) => {
let (n, m) = Self::f(Some(r));
root.borrow_mut().right = n;
(Some(root), m)
}
(None, None) => (Some(root.clone()), Some(root.clone())),
}
}
}