[Solved] 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.

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.

Example 1:

Machine Learning Projects
Input: root = [1,1,1,1,1,null,1]
Output: true

Example 2:

Machine Learning Projects
Input: root = [2,2,2,5,2]
Output: false

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • 0 <= Node.val < 100

Python Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
    
class Solution:
    def isUnivalTree(self, root: TreeNode) -> bool:
        stack = [root]
        prev = root.val
        while len(stack)!=0:
            x = stack.pop()
            if x==None:
                continue
            curr = x.val
            if prev!=curr:
                return False
            stack.append(x.left)
            stack.append(x.right)
            prev = curr
            
        return True
Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

Your email address will not be published. Required fields are marked *