Skip to content

Commit 0c7dd32

Browse files
committed
8-17-2020
1 parent 66f055d commit 0c7dd32

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
struct Solution;
2+
use crate::util::*;
3+
use std::cell::RefCell;
4+
use std::rc::Rc;
5+
6+
impl Solution {
7+
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
8+
let mut max_depth: i32 = 0;
9+
Self::traverse(&root, 1, &mut max_depth);
10+
max_depth
11+
}
12+
13+
fn traverse(root: &Option<Rc<RefCell<TreeNode>>>, depth: i32, max_depth: &mut i32) {
14+
if let Some(node) = root {
15+
if node.borrow().left.is_none() && node.borrow().right.is_none() {
16+
if depth > *max_depth {
17+
*max_depth = depth;
18+
}
19+
}
20+
Self::traverse(&node.borrow().left, depth + 1, max_depth);
21+
Self::traverse(&node.borrow().right, depth + 1, max_depth);
22+
}
23+
}
24+
}
25+
#[test]
26+
fn test() {
27+
assert_eq!(
28+
Solution::max_depth(tree!(3, tree!(9), tree!(20, tree!(15), tree!(7)))),
29+
3
30+
);
31+
}

src/_0617_merge_two_binary_trees.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
struct Solution;
2+
use crate::util::*;
3+
use std::cell::RefCell;
4+
use std::rc::Rc;
5+
impl Solution {
6+
pub fn merge_trees(
7+
mut t1: Option<Rc<RefCell<TreeNode>>>,
8+
mut t2: Option<Rc<RefCell<TreeNode>>>,
9+
) -> Option<Rc<RefCell<TreeNode>>> {
10+
Self::helper(&mut t1, &mut t2);
11+
t1
12+
}
13+
14+
fn helper(t1: &mut Option<Rc<RefCell<TreeNode>>>, t2: &mut Option<Rc<RefCell<TreeNode>>>) {
15+
if t1.is_some() && t2.is_some() {
16+
let (mut t1_, mut t2_) = (
17+
t1.as_mut().unwrap().borrow_mut(),
18+
t2.as_mut().unwrap().borrow_mut(),
19+
);
20+
t1_.val += t2_.val;
21+
Self::helper(&mut t1_.left, &mut t2_.left);
22+
Self::helper(&mut t1_.right, &mut t2_.right)
23+
} else if t2.is_some() {
24+
*t1 = t2.take();
25+
}
26+
}
27+
}
28+
29+
#[test]
30+
fn test() {
31+
let t1 = tree!(1, tree!(3, tree!(5), None), tree!(2));
32+
let t2 = tree!(2, tree!(1, None, tree!(4)), tree!(3, None, tree!(7)));
33+
let res = tree!(3, tree!(4, tree!(5), tree!(4)), tree!(5, None, tree!(7)));
34+
assert_eq!(Solution::merge_trees(t1, t2), res);
35+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,8 @@ mod _0561_array_partition_i;
166166
//
167167
mod _0605_can_place_flowers;
168168
//
169+
mod _0617_merge_two_binary_trees;
170+
//
169171
mod _0678_valid_parenthesis_string;
170172
//
171173
mod _0680_valid_palindrome_ii;

0 commit comments

Comments
 (0)