Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f3a85bd

Browse files
committed
univalued-binary-tree
1 parent 3843161 commit f3a85bd

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
- 746:检查整数及其两倍数是否存在
2626
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/check-if-n-and-its-double-exist.rs)
2727
- [leetcode](https://leetcode-cn.com/problems/check-if-n-and-its-double-exist/)
28+
- 965:单值二叉树
29+
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/univalued-binary-tree.rs)
30+
- [leetcode](https://leetcode-cn.com/problems/univalued-binary-tree/)
2831
- 1008:前序遍历构造二叉搜索树
2932

3033
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/construct-binary-search-tree-from-preorder-traversal.rs)
@@ -39,6 +42,7 @@
3942
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/maximum-points-you-can-obtain-from-cards.rs)
4043
- [leetcode](https://leetcode-cn.com/problems/running-sum-of-1d-array/)
4144
- 1678:设计 Goal 解析器
42-
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/goal-parser-interpretation.rs)
45+
46+
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/goal-parser-interpretation.rs)
4347
- [leetcode](https://leetcode-cn.com/problems/goal-parser-interpretation/)
4448

src/bin/univalued-binary-tree.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
20+
use std::rc::Rc;
21+
use std::cell::RefCell;
22+
23+
struct Solution;
24+
25+
impl Solution {
26+
// 递归
27+
pub fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
28+
match root {
29+
None => true,
30+
Some(r) => {
31+
let value = r.borrow().val;
32+
33+
let left_result = match &r.borrow().left {
34+
Some(left) => {
35+
if left.borrow().val != value {
36+
false
37+
} else {
38+
Solution::is_unival_tree(Some(Rc::clone(left)))
39+
}
40+
}
41+
None => true,
42+
};
43+
44+
let right_result = match &r.borrow().right {
45+
Some(right) => {
46+
if right.borrow().val != value {
47+
false
48+
} else {
49+
Solution::is_unival_tree(Some(Rc::clone(right)))
50+
}
51+
}
52+
None => true,
53+
};
54+
55+
left_result && right_result
56+
}
57+
}
58+
}
59+
}
60+
61+
fn main() {}

0 commit comments

Comments
 (0)