Home > OS >  Maximum Depth of N-ary Tree - swift
Maximum Depth of N-ary Tree - swift

Time:10-07

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

I've already solved this through other ways. I'm just trying to resolve it through this code. Trying to figure out what's incorrect for this. It currently returns incorrect results:

class Solution {
    func maxDepth(_ root: Node?) -> Int {
        guard let node = root else { return 0 }
        return node.children.map(maxDepth).max() ?? 0   1
    }
} 

Helper class if you wanted to test this on Xcode:

class Node {
    var value: Int
    var children: [Node] = []
    weak var parent: Node?
    
    init(value: Int) {
        self.value = value
    }
    
    func add(child: Node) {
        children.append(child)
        child.parent = self
    }
}

Example:

let one = Node(value: 1)
let two = Node(value: 2)
let three = Node(value: 3)

one.add(child: two)
two.add(child: three)
print("res", maxDepth(one)) // returns: 2. Expected: 3

I'm always returning 2 actually. Not sure why...

CodePudding user response:

Shout out to Martin for helping me figure this out.

Pro tip. For such leetcode style questions. The dumbest/simplest tests are the best.

The line below has 2 mistakes:

return node.children.map(maxDepth).max() ?? 1   1
  • The ?? is defaulting it to 0 1. Wrap the ?? in a parenthesis
  • The default should actually be 0. Not 1

So just do:

return (node.children.map(maxDepth).max() ?? 0)   1

I made that mistake because I almost never have any arithmetic operations after the ??

  • Related