sumCheckerHelper recursively calculates the sum of values for each subtree and checks if each node meets the sum tree condition. It returns an object containing the sum of the subtree rooted at the current node and a boolean indicating if the subtree meets the sum tree conditions.
1classNode{
2constructor(val){
3this.val = val;
4this.left = null;
5this.right = null;
6 }
7}
89const one = new Node(1);
10const two = new Node(2);
11const three = new Node(3);
1213three.right = two
14three.left = one
151617const ten = new Node(10);
18const twenty = new Node(20);
19const thirty = new Node(30);
20const tenLeft = new Node(10);
21const tenRight = new Node(10);
222324ten.right = thirty
25ten.left = twenty
26twenty.right = tenRight
27twenty.left = tenLeft
282930classSolution{
31isSumTree(node){
32if(!node) return1;
33if(!node.left && !node.right) return1;
34let result = this.sumCheckerHelper(node)
35return result.isSumTree
36 }
3738sumCheckerHelper(node){
39if(!node) return {sum : 0, isSumTree: 1};
40if(!node.left && !node.right) return {sum : node.val, isSumTree: 1};
41let left = this.sumCheckerHelper(node.left)
42let right = this.sumCheckerHelper(node.right)
43let totalSum = left.sum + right.sum + node.val
44let isSumTree = left.isSumTree && right.isSumTree && (node.val === right.sum + left.sum)
45return {sum : totalSum, isSumTree : isSumTree}
46 }
47}
48const solution = new Solution();
49console.log(solution.isSumTree(three));
50console.log(solution.isSumTree(ten));