python - Tree algorithm and sum value of node -
i'm working on programming exercise @ hackerrank. made data structure code this. couldn't figure out plan how can implement program sum value of tree node. give me advice code? if have fault in data structure i've made, please tell me abount that.
thank you.
[hackerrank exercise]
https://www.hackerrank.com/challenges/cut-the-tree
[code]
i wrote program , couldn't how can futher sum value of tree.
class tree: """ original tree structure representing input """ def __init__(self, value, position): self.value = value self.position = position self.connection = [] def set_connection(self, connection): self.connection.append(connection) def set_value(self, value): self.connection = value def get_value(self, position): return self.value def get_sum(self): return self.value def get_position(self): return self if __name__ == "__main__": # ----- initializing ------ n = int(input()) values = input().split() t = [] = 0 value in values: t.append(tree(int(value), a)) += 1 input_list = [] in range(n-1): in_con = input().split() t[int(in_con[0])-1].set_connection(int(in_con[1])-1) t[int(in_con[1])-1].set_connection(int(in_con[0])-1) input_list.append(in_con) # ----- start solve problem ----- ~~~~~~~~~~snip~~~~~~~~~~~~~~~~
i not going write full code, can follow pseudocode :
1) create tree node structure as: node{ int value; int sum; //sum of nodes under node(treating root) list<node> childs; } 2) totalsum = root.getsum()// represents sum of values in tree. 3)min =integer.max_value; each node in tree{ // below quantity represents sum of other half created removing incoming edge of current node. half = totalsum - node.getsum(); if(math.abs(node.getsum() - half) < min){ min = math.abs(node.getsum() - half); } } min value;
Comments
Post a Comment