Difference Between Sums of Odd and Even Levels in Binary Trees | Code Samurai
Question: calculate the difference between the sum of nodes at even level and sum of nodes at odd level.
Solution: recursion is the easiest way to solve this problem. At each non-null node of the tree, we have three things to do. 1) Find the difference between the node's left child with it's children by calling the function recursively on the node's left child. 2) Do the same thing for the node's right child. 3) Find the difference between the current node and the sum of it's left and right child.
Question: calculate the difference between the sum of nodes at even level and sum of nodes at odd level.
Solution: recursion is the easiest way to solve this problem. At each non-null node of the tree, we have three things to do. 1) Find the difference between the node's left child with it's children by calling the function recursively on the node's left child. 2) Do the same thing for the node's right child. 3) Find the difference between the current node and the sum of it's left and right child.
function diffBetween(pRootNode) { if (pRootNode === null || pRootNode === undefined) return 0; var lvalue = diffBetween(pRootNode.pLChild); var rvalue = diffBetween(pRootNode.pRChild); var result = pRootNode.nData - (lvalue + rvalue); return result; }
- Line 3 and 2, check for invalid input. This step acts as the case stopper for our recursion.
- Line 6: find the difference between the left child and its children.
- Line 7: find the difference between the right child and its children.
- Line 9: find the difference between the current node and its children.
- Line 10: finally returns the result.