HackerRank Python - XML2 - Find the Maximum Depth


You are given a valid XML document, and you have to print the maximum level of nesting in it. Take the depth of the root as 0.

  1. import xml.etree.ElementTree as etree
  2. maxdepth = 0
  3. def depth(elem, level):
  4. global maxdepth
  5. if (level == maxdepth):
  6. maxdepth += 1
  7. for child in elem:
  8. depth(child, level + 1)
  9. if __name__ == '__main__':
  10. n = int(input())
  11. xml = ""
  12. for i in range(n):
  13. xml = xml + input() + "\n"
  14. tree = etree.ElementTree(etree.fromstring(xml))
  15. depth(tree.getroot(), -1)
  16. print(maxdepth)

download android app