Leetcode 2236. Root Equals Sum of Children
Given a binary tree where the root node has an integer value val and two children with their own integer values left and right, determine if the value of the root node is equal to the sum of its children. The tree is guaranteed to have exactly three nodes: the root, its left child, and its right child.
Given the typical problem constraints and based on LeetCode’s platform, these assumptions will be considered:
/**
* 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 checkTree(TreeNode* root) {
if (root == nullptr || root->left == nullptr || root->right == nullptr) {
return false;
}
return (root->val == root->left->val + root->right->val);
}
};
root->left->val and root->right->val.root->val.true if they are equal, otherwise false.The time complexity of this solution is (O(1)) because:
The space complexity is also (O(1)) because only a constant amount of extra space is used.
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?