def rebuild_tree(doctype, parent_field):
 frappe.db.auto_commit_on_many_writes = 1
 right = 1
 result = frappe.db.sql((u"SELECT name FROM `tab%s` WHERE `%s`='' or `%s` IS NULL ORDER BY name ASC" % (doctype, parent_field, parent_field)))
 for r in result:
  right = rebuild_node(doctype, r[0], right, parent_field)
 frappe.db.auto_commit_on_many_writes = 0

def rebuild_tree ( doctype , parent_field ) : frappe . db . auto_commit_on_many_writes = 1 right = 1 result = frappe . db . sql ( ( u"SELECT name FROM `tab%s` WHERE `%s`='' or `%s` IS NULL ORDER BY name ASC" % ( doctype , parent_field , parent_field ) ) ) for r in result : right = rebuild_node ( doctype , r [ 0 ] , right , parent_field ) frappe . db . auto_commit_on_many_writes = 0
call rebuild_node for all root nodes .