Problem
Given a binary tree find the sum of nodes present at odd levels. That means excluding nodes at every alternate levels.
Given a binary tree find the sum of nodes present at odd levels. That means excluding nodes at every alternate levels.
Solution
We will a find the sum by recursively calling the function on left and right children of a node. While calling the function on any child node we will toggle a boolean flag to indicate whether this level is to include in the sum or not. If current level is to be included then add the current node's value to to the sum obtained from left and right children and return it. If the current level is not to be included then return only the sum of values returned from children.
We will a find the sum by recursively calling the function on left and right children of a node. While calling the function on any child node we will toggle a boolean flag to indicate whether this level is to include in the sum or not. If current level is to be included then add the current node's value to to the sum obtained from left and right children and return it. If the current level is not to be included then return only the sum of values returned from children.
No comments:
Post a Comment