Skip to content

Latest commit

 

History

History
44 lines (30 loc) · 1.05 KB

0965.md

File metadata and controls

44 lines (30 loc) · 1.05 KB

Level: Easy

Topic: Tree Binary Tree Depth First Search Breadth First Search

Question

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.

Input: root = [1,1,1,1,1,null,1]
Output: true

Intuition

Recursive:

  • all nodes must be the same value, use helper to maintain

Code

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

Recursive

public boolean isUnivalTree(TreeNode root) {
    return helper(root, root.val);
}

private boolean helper(TreeNode root, int val) {
    if (root == null)
        return true;
    return root.val == val && helper(root.left, val) && helper(root.right, val);
}