0

The input is array of string ["(1,2)","(10,2)"]

import ast
def TreeConstructor(strArr):

  # code goes here
  if len(strArr) == 0:
    return "true" 

  nodes = {}
  parent_exist = set()

  for ele in strArr:
    child, parent = ast.literal_eval(ele)
    child_count = nodes.get(parent, 0)
    child_count += 1
    if(child_count > 2):
      return "false"
  
    nodes[parent] = child_count
    parent_exist.add(child)

  no_parent_count = 0
  for node in nodes:
    if node not in parent_exist:
      no_parent_count += 1
  
  return "true" if no_parent_count == 1 else "false"

I'm trying to understand the porpose of this part in code

    child, parent = ast.literal_eval(ele)
    child_count = nodes.get(parent, 0)
    child_count += 1
    if(child_count > 2):
      return "false"
  
    nodes[parent] = child_count
    parent_exist.add(child) 

and why when i use eval like this : child, parent = eval(ele) i had an error : indentationerror: expected an indented block

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    You could use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through the code line by line while monitoring variables and their values, to see what's going on. Or just print the variables after (and perhaps before) each statement? Together with pen and paper, and [the Python documentation](https://docs.python.org/3/) it should be possible to figure out what's going on. – Some programmer dude Aug 31 '23 at 09:25
  • The purpose of that code is to add nodes to a tree and verify that it is a binary tree. Can you explain what specifically is not clear? – trincot Aug 31 '23 at 09:33

0 Answers0