-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths0617_merge_two_binary_trees.rs
61 lines (56 loc) · 1.71 KB
/
s0617_merge_two_binary_trees.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
use rustgym_util::*;
struct Solution;
//leetcode submit region begin(Prohibit modification and deletion)
// 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 merge_trees(
root1: Option<Rc<RefCell<TreeNode>>>,
root2: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
match (root1, root2) {
(Some(node1), Some(node2)) => {
let mut node1 = node1.borrow_mut();
let mut node2 = node2.borrow_mut();
Some(Rc::new(RefCell::new(TreeNode {
val: node1.val + node2.val,
left: Self::merge_trees(node1.left.take(), node2.left.take()),
right: Self::merge_trees(node1.right.take(), node2.right.take()),
})))
}
(None, Some(node2)) => Some(node2),
(Some(node1), None) => Some(node1),
_ => None,
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let t1 = tree!(1, tree!(3, tree!(5), None), tree!(2));
let t2 = tree!(2, tree!(1, None, tree!(4)), tree!(3, None, tree!(7)));
let res = tree!(3, tree!(4, tree!(5), tree!(4)), tree!(5, None, tree!(7)));
assert_eq!(Solution::merge_trees(t1, t2), res);
}
}