https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
We should return its max depth, which is 3.
Note:
The depth of the tree is at most 1000. The total number of nodes is at most 5000.
Here is my code, and also 1 test as an example Please comment about space and time complexity, I also made a recursive answer but I tend to think about BFS in an iterative way while using queue, and DFS in recursive way, although you can use a stack for it as well. so I a real interview I would probably go with BFS with a queue.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace TreeQuestions
{
// Definition for a Node.
public class Node
{
public int val;
public IList<Node> children;
public Node()
{
}
public Node(int _val, IList<Node> _children)
{
val = _val;
children = _children;
}
}
/// <summary>
/// https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
/// </summary>
[TestClass]
public class MaximumDepthOfN_aryTree
{
public int MaxDepth(Node root)
{
if (root == null)
{
return 0;
}
int maxDepth = 0;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
while (queue.Count > 0)
{
maxDepth++;
var queueSize = queue.Count;
for (int i = 0; i < queueSize; i++)
{
var current = queue.Dequeue();
if (current.children != null)
{
foreach (var child in current.children)
{
queue.Enqueue(child);
}
}
}
}
return maxDepth;
}
[TestMethod]
public void MaximumDepthOfN_aryTreeTest()
{
List<Node> node3 = new List<Node>();
node3.Add(new Node(5, null));
node3.Add(new Node(6, null));
List<Node> node1 = new List<Node>();
node1.Add(new Node(3, node3));
node1.Add(new Node(2, null));
node1.Add(new Node(4, null));
Node root = new Node(1, node1);
int result = MaxDepth(root);
Assert.AreEqual(3, result);
}
}
}