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.
Definition of N-ary Tree
1 | // Definition for a Node. |
DFS (Depth First Search)
DFS is usually easy to implement using recursion. The depth of N-ary tree is the maximum depth of its subtree (children) plus one.
1 | class Solution { |
BFS (Breadth First Search)
BFS travels the tree level by level. This is done by maintaining a queue and expanding the children nodes node by node. At each iteration, we also need to calculate its depth and push the depth together with the node in the queue.
1 | class Solution { |
Both BFS and DFS need to walk through the entire tree, and therefore, performance-wise, there is no much difference.
Support me and my work as a witness - witness thread by
Thank you! Some of My Contributions: SteemIt Tutorials, Robots, Tools and APIs
// Reposted to my blog for better indexing: https://helloacm.com/c-coding-exercise-find-maximum-depth-of-n-ary-tree/
题意:找出N叉树的最大深度。
上面这颗树,深度为3.
N叉树的C++定义
1 | // Definition for a Node. |
深度优先 DFS (Depth First Search)
用递归来实现深度优先最合适了。这题的解法就是递归的找出子树的深度,然后答案就是这些子树深度最深的那个加上一。
1 | class Solution { |
广度优先 BFS (Breadth First Search)
广度优先一层一层的遍例树,可以用队列来实现,每次从队列中取出一个节点,然后把子树结点依次的添加到队列中并计算当前深度。
1 | class Solution { |
两种方法都需要把整颗树走完才能算出最大深度,所以时间复杂度都是类似的。
// 同步到我的博客: https://justyy.com/archives/6444
支持我的工作 支持我成为 见证人
- 请在 这里 投我一票, 或者
- 设置我 为代理.
谢谢您! 我的贡献:SteemIt 工具、API接口、机器人和教程
股东工具
请注意:每次代理都是以最后一次输入的SP数量为标准,比如已经代理10 SP,想多代理5 SP则需要输入 最后的数字 15 SP(而不是 5!)
This page is synchronized from the post: ‘C++ Coding Exercise - Find Maximum Depth of N-ary Tree - 编程练习题:找出N叉树的深度’