#543
Easy Algorithms Diameter of binary tree
Tree Depth-First Search Binary Tree
65.1% acceptance
Feb 19, 2026
15548
1235
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
Solution
Rust
Time O(n)
Space O(n)
// 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::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn diameter_of_binary_tree(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut max_d = 0i32;
fn depth(node: &Option<Rc<RefCell<TreeNode>>>, max_d: &mut i32) -> i32 {
if let Some(n) = node {
let nb = n.borrow();
let l = depth(&nb.left, max_d);
let r = depth(&nb.right, max_d);
*max_d = (*max_d).max(l + r);
1 + l.max(r)
} else { 0 }
}
depth(&root, &mut max_d);
max_d
}
}