Given a binary 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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
/*
* ITERATIVE SOLUTION
*/
class Solution {
public int maxDepth(TreeNode node) {
if(node == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList();
queue.add(node); // add root node to the queue
int depth = 0 ;
while(!queue.isEmpty()) {
int size = queue.size(); // ıterate over all added sub nodes
for(int i = 0 ; i < size ; i++) { // add all sub nodes into queue
TreeNode currentNode = queue.remove();
if(currentNode.left != null) {
queue.add(currentNode.left);
}
if(currentNode.right != null) {
queue.add(currentNode.right);
}
}
depth ++; // increase depth by one after adding all sub nodes to queue
}
return depth;
}
}
// RECURSIVE SOLUTION O(N), O(N)
public int depth(TreeNode root, int sum) {
if (root == null) {
return sum;
}
return Math.max(depth(root.left,sum+1), depth(root.right,sum+1));
}