Created
October 17, 2014 17:10
-
-
Save piyushkandpal/df21edb6bc374832b0dd to your computer and use it in GitHub Desktop.
// algorithm solution for https://www.hackerrank.com/challenges/even-tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I used BFS to travel through the nodes. First, maintain an array separately to store the total number of child nodes + 1. So, you can initially assign all the leaf nodes with value 1 in this array. Now start from the last node and count the number of children for each node. This will work in bottom to top manner and the array that stores the number of child nodes will help in runtime to optimize the code. | |
Once you get the array after getting the number of children nodes for all the nodes, just counting the nodes with even number of nodes gives the answer. Note: I did not include root node in counting in final step. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment