Skip to content

Commit df6aa0e

Browse files
committed
feat: add rust solution to lcof problem: No.55 - ||
面试题55 - II. 平衡二叉树
1 parent a1b9ddf commit df6aa0e

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

lcof/面试题55 - II. 平衡二叉树/README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,54 @@ func depth(root *TreeNode) int {
196196
}
197197
```
198198

199+
### **Rust**
200+
201+
```rust
202+
// Definition for a binary tree node.
203+
// #[derive(Debug, PartialEq, Eq)]
204+
// pub struct TreeNode {
205+
// pub val: i32,
206+
// pub left: Option<Rc<RefCell<TreeNode>>>,
207+
// pub right: Option<Rc<RefCell<TreeNode>>>,
208+
// }
209+
//
210+
// impl TreeNode {
211+
// #[inline]
212+
// pub fn new(val: i32) -> Self {
213+
// TreeNode {
214+
// val,
215+
// left: None,
216+
// right: None
217+
// }
218+
// }
219+
// }
220+
use std::rc::Rc;
221+
use std::cell::RefCell;
222+
impl Solution {
223+
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
224+
match root {
225+
None => 0,
226+
Some(node) => {
227+
let node = node.borrow();
228+
1 + Self::dfs(&node.left).max(Self::dfs(&node.right))
229+
}
230+
}
231+
}
232+
pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
233+
match root {
234+
None => true,
235+
Some(node) => {
236+
let mut node = node.borrow_mut();
237+
let a = 10;
238+
(Self::dfs(&node.left) - Self::dfs(&node.right)).abs() <= 1
239+
&& Self::is_balanced(node.left.take())
240+
&& Self::is_balanced(node.right.take())
241+
}
242+
}
243+
}
244+
}
245+
```
246+
199247
### **...**
200248

201249
```
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Definition for a binary tree node.
2+
// #[derive(Debug, PartialEq, Eq)]
3+
// pub struct TreeNode {
4+
// pub val: i32,
5+
// pub left: Option<Rc<RefCell<TreeNode>>>,
6+
// pub right: Option<Rc<RefCell<TreeNode>>>,
7+
// }
8+
//
9+
// impl TreeNode {
10+
// #[inline]
11+
// pub fn new(val: i32) -> Self {
12+
// TreeNode {
13+
// val,
14+
// left: None,
15+
// right: None
16+
// }
17+
// }
18+
// }
19+
use std::rc::Rc;
20+
use std::cell::RefCell;
21+
impl Solution {
22+
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
23+
match root {
24+
None => 0,
25+
Some(node) => {
26+
let node = node.borrow();
27+
1 + Self::dfs(&node.left).max(Self::dfs(&node.right))
28+
}
29+
}
30+
}
31+
pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
32+
match root {
33+
None => true,
34+
Some(node) => {
35+
let mut node = node.borrow_mut();
36+
let a = 10;
37+
(Self::dfs(&node.left) - Self::dfs(&node.right)).abs() <= 1
38+
&& Self::is_balanced(node.left.take())
39+
&& Self::is_balanced(node.right.take())
40+
}
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)