Skip to content

Commit 701f6cd

Browse files
committed
Maximum depth of n-ary tree.
1 parent 62aefd3 commit 701f6cd

File tree

4 files changed

+63
-0
lines changed

4 files changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
Given a n-ary tree, find its maximum depth.
3+
4+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
5+
6+
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
7+
8+
 
9+
10+
Example 1:
11+
Input: root = [1,null,3,2,4,null,5,6]
12+
Output: 3
13+
14+
Example 2:
15+
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
16+
Output: 5
17+
 
18+
19+
Constraints:
20+
- The total number of nodes is in the range [0, 104].
21+
- The depth of the n-ary tree is less than or equal to 1000.
22+
*/
23+
/**
24+
* Definition for a Node.
25+
*/
26+
public class Node {
27+
public var val: Int
28+
public var children: [Node]
29+
public init(_ val: Int) {
30+
self.val = val
31+
self.children = []
32+
}
33+
}
34+
class Solution {
35+
func maxDepth(_ root: Node?) -> Int {
36+
if root?.val == nil { return 0 }
37+
var depth = 0
38+
for child in root!.children {
39+
depth = max(depth, maxDepth(child))
40+
}
41+
return depth + 1
42+
}
43+
}
44+
45+
let s = Solution()
46+
let node = Node(1)
47+
let node1 = Node(3)
48+
node1.children = [Node(5), Node(6)]
49+
node.children = [node1, Node(2), Node(4)]
50+
let r = s.maxDepth(node)
51+
print(r)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/559.Maximum Depth of N-ary Tree.playground/playground.xcworkspace/contents.xcworkspacedata

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@
110110
106. [Reverse String II](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/541.Reverse%20String%20II.playground/Contents.swift)
111111
107. [Student Attendance Record I](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/551.Student%20Attendance%20Record%20I.playground/Contents.swift)
112112
108. [Reverse Words in a String III](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/557.Reverse%20Words%20in%20a%20String%20III.playground/Contents.swift)
113+
109. [Maximum Depth of N-ary Tree](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/559.Maximum%20Depth%20of%20N-ary%20Tree.playground/Contents.swift)
113114

114115
#### Medium
115116

0 commit comments

Comments
 (0)