/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/* Devide and conquer
public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}
*/

// Traversal
public class Solution {
    private int depth;
    public int maxDepth(TreeNode root) {
        depth = 0;
        helper(root, 1);
        return depth;
    }
    
    private void helper(TreeNode root, int currentDepth) {
        if (root == null) {
            return;
        }
        depth = depth > currentDepth ? depth : currentDepth;
        helper(root.left, currentDepth + 1);
        helper(root.right, currentDepth + 1);
    }
}
Advertisements