DFS
if (root == null)
return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
// This is the part that counts the number of nodes.
return 1 + Math.max(left, right);
BFS
same as the level order traversal. You just need to return the size or length of the list at the end.
List<List<Integer>> levels = new ArrayList<>();
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int level_length = queue.size();
List<Integer> currLevel = new ArrayList<>();
for (int i = 0; i < level_length; i++) {
TreeNode node = queue.remove();
currLevel.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
levels.add(currLevel);
}
return levels.size();
'Algorithms and Data Structures > Leetcode' 카테고리의 다른 글
Leetcode 700. Search in a Binary Search Tree (0) | 2022.03.21 |
---|---|
Leetcode 102 - Binary Tree Level Order Traversal (0) | 2022.03.18 |