DDSA Solutions

965. Univalued Binary Tree

Time: O(n)
Space: O(n)

Problem Overview

Univalued Binary Tree (Easy) asks you to solve a structured algorithmic task. This is a common Tree / Depth-First Search pattern in coding interviews. DFS; return false if any node's value differs from its parent or if any child subtree is not univalued.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

DFS; return false if any node's value differs from its parent or if any child subtree is not univalued.

Related patterns: Tree, Depth-First Search, Breadth-First Search

965.cs
C#
// Approach: DFS; return false if any node's value differs from its parent or if any child subtree is not univalued.
// Time: O(n) Space: O(n)

public class TreeNode(TreeNode root)
    {
        if (root == null)
            return true;
        if (root.left != null && root.left.val != root.val)
            return false;
        if (root.right != null && root.right.val != root.val)
            return false;
        return IsUnivalTree(root.left) && IsUnivalTree(root.right);
    }
}
Was this solution helpful?

Related Problems