104.Maximum Depth of Binary Tree
Solution 1-Recursion-DFS
In my opinion, the time complexity of the solution is O(n)
, wheren
is the number of nodes in the tree which we visit once. Also, the space complexity is O(n)
due to the recursive stack being used.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
return (1 + Math.max(maxDepth(root.left), maxDepth(root.right)));
}
}
Solution 2-BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int depth = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int currentQueueSize = queue.size();
while(currentQueueSize > 0){
TreeNode tmp = queue.poll();
if(tmp.left != null){
queue.offer(tmp.left);
}
if(tmp.right != null){
queue.offer(tmp.right);
}
currentQueueSize -= 1;
}
depth += 1;
}
return depth;
}
}