Leetcode 2236. Root Equals Sum of Children
Given a binary tree with just one node and its two children, root and exactly two children nodes named left and right. Check if the value of the root node equals the sum of the values of its two children nodes.
Before proceeding with the solution, let’s clarify some points:
Assuming the tree will always have exactly three nodes, i.e., a root and its two children, and node values are non-negative integers.
Here is the Java code that implements the solution to this problem:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public boolean checkTree(TreeNode root) {
if (root == null || root.left == null || root.right == null) {
// If the root is null or it does not have exactly two children, return false.
return false;
}
// Check if the root value is equal to the sum of its left and right children.
return root.val == root.left.val + root.right.val;
}
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode leftChild = new TreeNode(4);
TreeNode rightChild = new TreeNode(5);
TreeNode root = new TreeNode(9, leftChild, rightChild);
System.out.println(solution.checkTree(root)); // Output should be true as 9 = 4 + 5
TreeNode root2 = new TreeNode(10, leftChild, rightChild);
System.out.println(solution.checkTree(root2)); // Output should be false as 10 != 4 + 5
}
}
The time complexity of this solution is O(1) since it performs a constant number of operations regardless of the input size.
Thus, our approach is optimal and meets the problem’s requirements effectively.
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?