1

Assuming that r is the root of a tree (may be non-binary), c is a child of r, and each node contains an integer.

Algorithm findMax(r)
if r = null return null
int maxValue = r.value
if r.isLeaf return maxValue;
for each child c of r do{
    if findMax(c) > maxValue
        maxValue = findMax(c)
}
return maxValue
4
  • What are your own thoughts on this? Also, did you mean maxValue = findMax(c) and if findMax(c) > maxValue? Commented Oct 22, 2018 at 16:24
  • I think that it would be O(n^2) however the part I am unsure of is that the number of children for each node could be different. Commented Oct 22, 2018 at 16:26
  • @BenTilden Does my post answer you? Commented Oct 23, 2018 at 4:09
  • Yes thank you @DavidWinder Commented Oct 23, 2018 at 14:37

1 Answer 1

1

Currently it does have O(n) complexity when consider n to be number of node in the tree.

For each child-node of the root you call recursive function to all sub-tree root in c. So basically, you preform DFS on this graph which make in O(V+E) -> in your case, when the graph is a tree, it equel to O(V).

Notice, that you call recursive function of findMax in the if-statement - if it true you calculate it again - which increase complexity to O(2*n). Calculate the findMax function once, assign its result to local var and check and update the maxValue with it will reduce complexity to O(n).

Sign up to request clarification or add additional context in comments.

Comments

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.