Skip to content

Instantly share code, notes, and snippets.

@mckelvin
Created June 28, 2016 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mckelvin/f6b97a3c8fae969ff6d9505946759991 to your computer and use it in GitHub Desktop.
Save mckelvin/f6b97a3c8fae969ff6d9505946759991 to your computer and use it in GitHub Desktop.
# coding: utf-8
input_data = [
{
"title": "WTF?",
"data_1": "5525577",
"parentid": "0",
"key": "7612"
}, {
"title": "用户管理",
"data_1": "552559277",
"parentid": "7612",
"key": "7667"
}, {
"title": "开户",
"data_1": "",
"parentid": "7612",
"key": "7668"
}, {
"title": "用户资料修改",
"data_1": "552559279",
"parentid": "7612",
"key": "7669"
}, {
"title": "密码修改",
"data_1": "5555279",
"parentid": "7669",
"key": "76691"
}, {
"title": "用户名修改",
"data_1": "55279",
"parentid": "7669",
"key": "76692"
},
]
def main():
dct = {}
reverse_dct = {}
for item in input_data:
if "data_1" not in item:
continue
parent = item["parentid"]
current = item["key"]
dct.setdefault(parent, []).append(current)
reverse_dct[current] = parent
# find root
root = input_data[0]["key"]
while root in reverse_dct:
root = reverse_dct[root]
root = dct[root][0]
print "root: %s" % root
# dfs
stack = [(root, 0)]
while stack:
curr, indent = stack.pop()
print " " * indent, curr
for child_id in dct.get(curr, []):
stack.append((child_id, indent + 2))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment