Maximum Depth of Binary Tree
3
/ \
9 20
/ \
15 7Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
// 1 -> 1
// 1 -> 2->3,4
public int maxDepth(TreeNode root) {
// counter = 0
// recursively come to end of each node and count all nodes,
// then change max only if depth is bigger & .left or .right is null
iterate(root, 0);
return max;
}
public void iterate(TreeNode node, int count) {
if (node == null) {
max = Math.max(max, count);
return;
}
count++;
iterate(node.left, count);
iterate(node.right, count);
}
}Last updated