Skip to content

Commit ebac95e

Browse files
committed
q1382
1 parent 3d79f3d commit ebac95e

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

src/tree/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,5 @@ macro_rules! tree {
135135

136136
mod q108;
137137
mod q95;
138-
mod q129;
138+
mod q129;
139+
mod q1382;

src/tree/q1382.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//! Link:https://leetcode-cn.com/problems/balance-a-binary-search-tree
2+
use super::*;
3+
struct Solution{}
4+
5+
6+
7+
impl Solution {
8+
pub fn balance_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
9+
let mut nums: Vec<i32> = Vec::new();
10+
11+
// 中序深度遍历拿到有序数组
12+
fn build_sort_vector(r: Option<Rc<RefCell<TreeNode>>>, n: &mut Vec<i32>) {
13+
if let Some(v) = r {
14+
build_sort_vector(RefCell::borrow(&v).left.clone(), n);
15+
n.push(RefCell::borrow(&v).val);
16+
build_sort_vector(RefCell::borrow(&v).right.clone(), n);
17+
}
18+
}
19+
;
20+
21+
// 递归构建二叉平衡术
22+
fn build_bbst(n: &Vec<i32>, s: usize, e: usize) -> Option<Rc<RefCell<TreeNode>>> {
23+
if s > e {
24+
return None
25+
}
26+
27+
let m = (s + e) / 2;
28+
let mut root = TreeNode::new(n[m]);
29+
if s == e {
30+
return Some(Rc::new(RefCell::new(root)))
31+
}
32+
33+
if m >= 1 {
34+
let left_node = build_bbst(n, s, m - 1);
35+
root.left = left_node.clone();
36+
}
37+
38+
let right_node = build_bbst(n, m + 1, e);
39+
root.right = right_node.clone();
40+
return Some(Rc::new(RefCell::new(root)))
41+
}
42+
43+
build_sort_vector(root, &mut nums);
44+
build_bbst(&nums, 0, nums.len()-1)
45+
}
46+
}
47+
48+
49+
#[cfg(test)]
50+
mod tests {
51+
use super::*;
52+
53+
#[test]
54+
fn test_1() {
55+
let trees = Solution::balance_bst(tree!(1, null, 2, null, 3, null, 4, null));
56+
println!("{:?}", trees.unwrap());
57+
58+
}
59+
}

0 commit comments

Comments
 (0)