LeetCode 2236: Root Equals Sum of Children
Problem Description
Explanation
To solve this problem, we can do a simple check at the root node to see if its value is equal to the sum of its left and right children's values. We can recursively traverse the tree to check this condition. If the root is null or the tree does not consist of exactly 3 nodes, we can return false. We can define a recursive function to check this condition and return true if it holds for the current node.
- Time complexity: O(n) where n is the number of nodes in the tree.
- Space complexity: O(h) where h is the height of the tree.
Solutions
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public boolean rootEqualsSumOfChildren(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return false;
}
return checkSum(root);
}
private boolean checkSum(TreeNode node) {
if (node == null) {
return true;
}
int sumChildren = 0;
if (node.left != null) {
sumChildren += node.left.val;
}
if (node.right != null) {
sumChildren += node.right.val;
}
return node.val == sumChildren && checkSum(node.left) && checkSum(node.right);
}
}
Loading editor...