104 Maximum Depth of Binary Tree

Question:

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.

Lesson Learned:

// 似乎用boolean的题可以用 return xxx && yyy来做, int的题可以用 return xxx + yyy来做

第二次的update,我用了只扫描path的方法,因为数level这种还是直接用path的template省的用脑子想了。

Code:

/**
 * 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 helper(root);
    }
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 似乎用boolean的题可以用 return xxx && yyy来做, int的题可以用 return xxx + yyy来做
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

updated (12.19.15)

/**
 * 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 helper(root);
    }
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null) {
            return 1 + helper(root.right);
        }
        if (root.right == null) {
            return 1 + helper(root.left);
        }
        return 1 + Math.max(helper(root.left), helper(root.right));
    }
}