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. Here is the implementation in JavaScript:
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; }
Explanation: the method takes in the root node of the binary tree that users want to compute the difference. Here are the steps:
- 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.
If you have any comment, please post. Also if there is any part that is not clear, please also let me know :)