LeetCode | 965. Single value binary tree
OJ link
- First, determine whether the tree is empty. If it is empty, it will be true directly.
- Then determine whether the val of the left subtree is different from the val of the root.
- Then determine whether the val of the right subtree is different from the val of the root.
- Finally recurse the left subtree and right subtree
bool isUnivalTree(struct TreeNode* root) {
if(root == NULL)
return true;
if(root->left && root->left->val != root->val)
return false;
if(root->right && root->right->val != root->val)
return false;
return isUnivalTree(root->left) && isUnivalTree(root->right);
}