Univalued Binary Tree - Complete Solution Guide
Univalued Binary Tree is LeetCode problem 965, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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
Detailed Explanation
The problem asks us to determine if a given binary tree is 'uni-valued'. A binary tree is uni-valued if every node in the tree has the same value. The input is the root of a binary tree, and the output should be a boolean: `true` if the tree is uni-valued, and `false` otherwise. The constraints specify the number of nodes is between 1 and 100, and node values are between 0 and 99.
Solution Approach
The solution uses a recursive Depth-First Search (DFS) approach. We start by storing the value of the root node. Then, we recursively traverse the tree, comparing the value of each node with the stored root value. If we encounter a node with a different value, we immediately return `false`. If we reach a null node, we return `true`. The recursion continues until all nodes have been visited (or a node with a different value is found).
Step-by-Step Algorithm
- Step 1: Check if the root is null. If it is, return true (an empty tree is considered uni-valued).
- Step 2: Store the value of the root node in a variable (e.g., `val`).
- Step 3: Define a recursive helper function `is_unival(node)` or `isUnivalTreeHelper(node, val)` that takes a node as input.
- Step 4: Inside the helper function, check if the node is null. If it is, return `true`.
- Step 5: If the node is not null, compare its value with the stored root value (`val`).
- Step 6: If the node's value is different from `val`, return `false`.
- Step 7: If the node's value is the same as `val`, recursively call the helper function for the left and right subtrees: `return is_unival(node.left) and is_unival(node.right)`.
- Step 8: Call the helper function with the root node initially: `return is_unival(root)`.
Key Insights
- Insight 1: We can traverse the tree using Depth-First Search (DFS) to check each node's value.
- Insight 2: We need to compare each node's value with the value of the root node. If any node has a different value, the tree is not uni-valued.
- Insight 3: The base case for the recursive DFS is when we reach a null node. In that case, we return `true` because a null node doesn't violate the uni-valued property.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(h)
Topics
This problem involves: Tree, Depth-First Search, Breadth-First Search, Binary Tree.
Companies
Asked at: Twilio.