- Easy
- A binary tree is uni-valued if every node in the tree has the same value.
- Given the
root
of a binary tree, returntrue
if the given tree is uni-valued, orfalse
otherwise. - https://leetcode.com/problems/univalued-binary-tree/
Runtime: 28 msMemory Usage: 14.3 MB
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
if root.left:
if root.left.val!=root.val:
return False
if root.right:
if root.right.val!=root.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
{% hint style="info" %} Simple recursive method. We only have to return the 'False situations' instead considering all the correct ones. {% endhint %}