August 7, 2016 · LeetCode Java Algorithm

LeetCode - 104 - Maximum Depth of Binary Tree

Problem
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.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

Note: Depth is started to count at 1. Try it out : https://leetcode.com/problems/maximum-depth-of-binary-tree/

Java 1ms

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
            return searchDepth(root,1);
    }
    public int searchDepth(TreeNode root,int initDepth){
        if (root == null){
            return 0;
        }else if (root.left == null && root.right == null){
            return initDepth;
        }else if (root.left != null && root.right == null){
            return searchDepth(root.left, initDepth + 1);
        }else if (root.right != null && root.left == null){
            return searchDepth(root.right,initDepth+1);
        }else if (root.right != null && root.left != null){
            int leftDepth = searchDepth(root.left , initDepth+1);
            int rightDepth = searchDepth(root.right, initDepth+1);
            return leftDepth > rightDepth?leftDepth:rightDepth;
        }
        return 0;
    }
}