0

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
  • 1
    Try incrementing a counter when you go deeper with {, but decrementing when you close out with }. Each time, check if your counter is greater than your current max. Commented Mar 12, 2015 at 9:32

5 Answers 5

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This worked but can u suggest me some tutorial on other such functions like map. Actually I have to do some detailed analysis on json tree.
this one is pretty readable
this is a nice solution
0

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

1 Comment

I also want to know the number of children at each level.
0

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')))

Comments

0

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

Comments

0

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)

1 Comment

IMO, locking should be done to count_global, which I did not do!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.