Skip to content

Commit

Permalink
create 0543-diameter-of-binary-tree.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
rmrt1n committed Jun 27, 2023
1 parent 39611ac commit 87320d3
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions rust/0543-diameter-of-binary-tree.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn diameter_of_binary_tree(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
fn dfs(root: Option<Rc<RefCell<TreeNode>>>) -> (i32, i32) {
match root {
None => (0, 0),
Some(node) => {
let (l_diameter, l_max) = dfs(node.borrow().left.clone());
let (r_diameter, r_max) = dfs(node.borrow().right.clone());
(
1 + l_diameter.max(r_diameter),
l_max.max(r_max.max(l_diameter + r_diameter)),
)
}
}
}

dfs(root).1
}
}

0 comments on commit 87320d3

Please sign in to comment.