#965
Easy Algorithms Univalued binary tree
Tree Depth-First Search Breadth-First Search Binary Tree
72.9% acceptance
Feb 27, 2026
1977
68
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
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 is_unival_tree(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>) -> bool {
fn check(node: &Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, val: i32) -> bool {
match node { None => true, Some(n) => { let n = n.borrow(); n.val == val && check(&n.left, val) && check(&n.right, val) } }
}
match &root { None => true, Some(n) => check(&root, n.borrow().val) }
}
}