Skip to content

Commit 96231cd

Browse files
solves max depth of n ary tree
1 parent e74dfac commit 96231cd

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@
146146
| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree) | Easy | [![Java](assets/java.png)](src/DiameterOfBinaryTree.java) [![Python](assets/python.png)](python/diameter_of_binary_tree.py) |
147147
| 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i) | Easy | [![Java](assets/java.png)](src/StudentAttendanceRecordI.java) [![Python](assets/python.png)](python/student_attendance_record_I.py) |
148148
| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii) | Easy | [![Java](assets/java.png)](src/ReverseWordsInStringIII.java) [![Python](assets/python.png)](python/reverse_words_in_string_iii.py) |
149-
| 559 | [Maximum Depth of N-Ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) | Easy | |
149+
| 559 | [Maximum Depth of N-Ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) | Easy | [![Java](assets/java.png)](src/MaximumDepthOfNAryTree.java) [![Python](assets/python.png)](python/maximum_depth_of_n_ary_tree.py) |
150150
| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i) | Easy | |
151151
| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) | Easy | |
152152
| 566 | [Reshape The Matrix](https://leetcode.com/problems/reshape-the-matrix) | Easy | |

python/maximum_depth_of_n_ary_tree.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Definition for a Node.
2+
class Node:
3+
def __init__(self, val=None, children=None):
4+
self.val = val
5+
self.children = children
6+
7+
8+
class Solution:
9+
def maxDepth(self, root: Node) -> int:
10+
if root is None: return 0
11+
max_depth = 0
12+
for child in root.children:
13+
max_depth = max(max_depth, self.maxDepth(child))
14+
return 1 + max_depth

src/MaximumDepthOfNAryTree.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.List;
2+
3+
class Node {
4+
public int val;
5+
public List<Node> children;
6+
7+
public Node() {}
8+
9+
public Node(int _val) {
10+
val = _val;
11+
}
12+
13+
public Node(int _val, List<Node> _children) {
14+
val = _val;
15+
children = _children;
16+
}
17+
};
18+
19+
public class MaximumDepthOfNAryTree {
20+
public int maxDepth(Node root) {
21+
if (root == null) return 0;
22+
int maxDepth = 0;
23+
for (Node child : root.children) {
24+
maxDepth = Math.max(maxDepth, maxDepth(child));
25+
}
26+
return 1 + maxDepth;
27+
}
28+
}

0 commit comments

Comments
 (0)