Skip to content

Instantly share code, notes, and snippets.

# Enter your code here. Read input from STDIN. Print output to STDOUT
T = raw_input()
#print T
jumps = {}
for i in range(int(T)):
L,S = raw_input().split(',')
ladder_dict = { k:v for k,v in (d.split(',') for d in iter(raw_input().split())) }
snake_dict = { k:v for k,v in (d.split(',') for d in iter(raw_input().split())) }
ladder_dict.update(snake_dict)
jumps = ladder_dict
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.
@piyushkandpal
piyushkandpal / gist:66ff7c9bfef129773e56
Created October 17, 2014 17:07
Tree traversal in python
from collections import namedtuple
from sys import stdout
Node = namedtuple('Node', 'data, left, right')
tree = Node(1,
Node(2,
Node(4,
Node(7, None, None),
None),
Node(5, None, None)),
// solution for https://www.hackerrank.com/challenges/even-tree
#include <iostream>
#include <fstream>
#include <map>
#include <deque>
#include <vector>
#include <cstring>
#include <algorithm>