问题
I have a tree of the form:
{
"id":442500000904671234,
"reply":0,
"children":[
{
"id":442500532536893440,
"reply":1,
"children":[
{
"id":442500826561785856,
"reply":1,
"children":[
{
"id":442501277688545280,
"reply":1,
"children":[
{
"id":442501561940709376,
"reply":1,
"children":[
{
"id":442501884709199872,
"reply":1,
"children":[
]
}
]
}
]
}
]
}
]
},
{
"id":442500099315597312,
"reply":0,
"children":[
]
}
]
}
How do I find maximum depth of the tree in python?
回答1:
You can parse JSON with python's json library and then calculate depth with recursive function.
import json
def depth(jsn):
if jsn.has_key('children'):
return 1 + max([0] + map(depth, jsn['children']))
else:
return 1
j = json.load(file('your_file.json'))
print depth(j)
回答2:
You can use a stack to push the { and then when you meet a } before you pop you check if your current depth is greater than the maximum depth that you got so far, that is if the stack.count is greater than the maximum count already achieved.
I'll update my answer after work with a code example
回答3:
What about loading json into dict
and traversing tree. At least should give some ideas to go further.
import json
def depth(root):
if root is None:
return 0
if isinstance(root, list):
return max(map(depth, root)) + 1
if not isinstance(root, dict):
return 1
return max(depth(v) for k, v in root.items()) + 1
print depth(json.load(file('your_data.json')))
回答4:
I think you can just walk the tree using DFS or BFS and count the depth as you go:
#load in your data
json_tree = json.loads(your_data)
depth = 0
if json_tree:
depth += 1
#add a root node + it's depth
to_visit = [(json_tree, depth)]
max_depth = 0
while to_visit:
#get first from the list
current = to_visit.pop(0)
#if depth greater than the current max update max
if current[1] > max_depth:
max_depth = current[1]
# append all children to the list with increased depth
for child in current[0]['children']:
to_visit.append((child, current[1] + 1))
print(max_depth)
the benefit of doing it this way is that you actually go over your data structure rather than rely on the string representation
回答5:
convert json to dict,
count_global = 0
def find_depth(tree_dict=None, count=0):
if not tree_dict['children']:
global count_global
if count_global < count:
count_global = count
for child in tree_dict['children']:
count = count + 1
find_depth(child, count)
来源:https://stackoverflow.com/questions/29005959/depth-of-a-json-tree