Leetcode 965. Univalued Binary Tree
A binary tree is univalued if every node in the tree has the same value.
Given the root of a binary tree, return true if the tree is univalued, or false otherwise.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
To determine if a binary tree is univalued, we can perform a Depth-First Search (DFS) traversal (either recursively or iteratively). We can start from the root and check if every node in the tree has the same value as the root.
Steps:
#include <iostream>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
// Base case: if root is nullptr, the tree is trivially univalued
if (root == nullptr) return true;
// Store the root's value
int rootValue = root->val;
// Helper function to perform DFS
return dfs(root, rootValue);
}
private:
bool dfs(TreeNode* node, int val) {
if (node == nullptr) return true;
if (node->val != val) return false;
return dfs(node->left, val) && dfs(node->right, val);
}
};
int main() {
// Example usage:
// Constructing a univalued binary tree where all nodes have the value 1.
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(1);
root->right = new TreeNode(1);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(1);
Solution sol;
bool result = sol.isUnivalTree(root);
std::cout << (result ? "True" : "False") << std::endl; // Output should be True
return 0;
}
The solution involves traversing every node in the binary tree once.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?