Find the level in a binary tree with given sum K
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
Algorithm:
One of the popular traversal techniques to solve this kind of problems is level order tree traversal (Read more: Level Order Traversal on a Binary Tree) where we use the concept of BFS with some modifications.
1. Set a variable level=0 & declare a variable of type tree* named temp. level is a flag for the current level & temp stores tree node to be processed.
2. Set cur_sum=0
3. if(!root) // root is NULL
return -1; //no such level exists
4. q=createQueue() //to store pointers to tree node
5. EnQueue(q,root);
6. EnQueue(q,NULL);
Every time, we EnQueue a NULL to reflect the end of current level. Same way while processing when NULL is found, it reveals that end of current level.
8. If program control comes out of while loop then surely no level has a sum K. Thus print no level has sum K
Example:
C++ code to find the level in a binary tree with given sum K
Output
need an explanation for this answer? contact us directly to get an explanation for this answer