Solving Leetcode Interviews in Seconds with AI: Univalued Binary Tree
Introduction
In this blog post, we will explore how to solve the LeetCode problem "965" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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: Input: root = [1,1,1,1,1,null,1] Output: true Example 2: 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
Explanation
Here's the breakdown of the approach, complexity, and the Python code:
High-Level Approach:
- Use Depth-First Search (DFS) to traverse the tree.
- Compare the value of each node with the value of the root node.
- If any node's value differs from the root's value, the tree is not uni-valued.
Complexity:
- Runtime Complexity: O(N), where N is the number of nodes in the tree.
- Storage Complexity: O(H), where H is the height of the tree. In the worst case (skewed tree), H = N; in the best case (balanced tree), H = log N.
Code
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isUnivalTree(root: TreeNode) -> bool:
if not root:
return True
val = root.val
def is_unival(node: TreeNode) -> bool:
if not node:
return True
if node.val != val:
return False
return is_unival(node.left) and is_unival(node.right)
return is_unival(root)