[LeetCode] 559. Maximum Depth of N-ary Tree
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 559. 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
.
1 /* 2 // Definition for a Node. 3 class Node { 4 public int val; 5 public List<Node> children; 6 7 public Node() {} 8 9 public Node(int _val,List<Node> _children) { 10 val = _val; 11 children = _children; 12 } 13 }; 14 */ 15 class Solution { 16 public int maxDepth(Node root) { 17 if (root == null) { 18 return 0; 19 } 20 int max = 0; 21 for(Node child : root.children) { 22 max = Math.max(maxDepth(child), max); 23 } 24 return max + 1; 25 } 26 }
Solution 2. BFS(tracking the number of nodes that need to be visited at each level)
1 class Solution { 2 public int maxDepth(Node root) { 3 if(root == null) { 4 return 0; 5 } 6 int level = 0; 7 int currLevelCount = 1; 8 int nextLevelCount = 0; 9 Queue<Node> queue = new LinkedList<>(); 10 queue.add(root); 11 while(!queue.isEmpty()) { 12 Node currNode = queue.poll(); 13 currLevelCount--; 14 for(Node child : currNode.children) { 15 queue.add(child); 16 nextLevelCount++; 17 } 18 if(currLevelCount == 0) { 19 level++; 20 currLevelCount = nextLevelCount; 21 nextLevelCount = 0; 22 } 23 } 24 return level; 25 } 26 }
Follow up: Can you implement a BFS to a certain depth?
以上是关于[LeetCode] 559. Maximum Depth of N-ary Tree的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode559. Maximum Depth of N-ary Tree
[LeetCode&Python] Problem 559. Maximum Depth of N-ary Tree
Leetcode 559. Maximum Depth of N-ary Tree
559. Maximum Depth of N-ary Tree